c#winform多线程假死(不能拖动窗口,窗口未响应)(自己用)
程序员文章站
2022-06-10 18:30:25
...
修改前
public delegate void treeinvoke(int i);
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Console.WriteLine("AAA");
System.Threading.Thread th = new System.Threading.Thread(new System.Threading.ThreadStart(this.startupdate));
th.IsBackground = true;
th.Start();
Console.WriteLine("BBB");
}
private void startupdate()
{
Console.WriteLine("CCC");
this.BeginInvoke(new treeinvoke(this.UpdateTreeView), 0);
Console.WriteLine("DDD");
}
private void UpdateTreeView(int j)
{
try
{
Console.WriteLine("EEE");
Thread.Sleep(5000);
Console.WriteLine("FFF");
}
catch (Exception ex)
{
}
}
修改后:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Threading;
using System.Text.RegularExpressions;
using System.Net;
namespace test
{
public partial class Form1 : Form
{
public delegate void treeinvoke(int i);
int num1 = 0;
int num2 = 10000;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Console.WriteLine("AAA");
for (int i = 0; i < 5000; i++)
{
ThreadPool.QueueUserWorkItem(startupdate, i);
}
Console.WriteLine("BBB");
}
private delegate void updateui();
private void TimeEvent(object source, System.Timers.ElapsedEventArgs e)
{
this.BeginInvoke(new updateui(upui));
}
private void upui()
{
label1.Text = num1.ToString() + "/" + num2.ToString();
}
private void startupdate(object c)
{
System.DateTime dt = DateTime.Now;
Console.WriteLine("CCC");
UpdateTreeView(int.Parse(c.ToString()));
Console.WriteLine("DDD");
}
private void UpdateTreeView(int j)
{
//反正这里执行耗时间操作Start
try
{
string strPageData = GetHttp("http://news.163.com/rank/", Encoding.GetEncoding("GB2312"));
this.BeginInvoke(new updateui(upui));//这里更新UI
Console.WriteLine(j.ToString());
num1 = j;
}
catch (Exception ex)
{
}
//反正这里执行耗时间操作End
}
public static string GetHttp(string url, Encoding encode)
{
string strResult;
try
{
WebClient client = new WebClient();
client.Encoding = encode;
strResult = client.DownloadString(url);
}
catch
{
strResult = "";
}
return strResult;
}
}
}
上一篇: pygame学习笔记(3):运动速率、时间、事件、文字
下一篇: 大葱根的作用,一根大葱三味药