c#winform多线程假死(不能拖动窗口,窗口未响应)有关问题
c#winform多线程假死(不能拖动窗口,窗口未响应)问题,在线等public delegate void treeinvoke(int i)publi
c#winform多线程假死(不能拖动窗口,窗口未响应)问题,在线等
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)
{
}
}
winform中,为什么运行点击button1的时候,会出现假死?不是异步执行的吗?为什么非要等执行完Thread.Sleep(5000);后才可以拖动窗口?
另外,就算我不用Thread.Sleep(5000);如果我这里读取数据库时间太长,也会出现假死,为什么呢,异步。。。。
在线等,谢谢
在线急等,谢谢大家解答 c#winform多线程假死问题
[解决办法]
不清楚LZ想干什么!
用Task,替代 Thread
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Console.WriteLine("AAA");
Task.Factory.StartNew(() =>
{
this.startupdate();
});
Console.WriteLine("BBB");
}
private void startupdate()
{
Console.WriteLine("CCC");
Task.Factory.StartNew(() =>
{
this.UpdateTreeView(0);
});
Console.WriteLine("DDD");
}
private void UpdateTreeView(int j)
{
try
{
Console.WriteLine("EEE");
Thread.Sleep(5000);
Console.WriteLine("FFF");
}
catch (Exception ex)
{
}
}
[解决办法]Control.BeginInvoke会通知主线程执行,也就是说UpdateTreeView在主线程执行。
B - E -F是主线程
C-D是子线程
[解决办法]去掉BeginInvoke,直接this.UpdateTreeView()
[解决办法]