UI无响应,线程疑问
点击按钮之后,程序就无响应了,应该是UI假死,这种该如何做呢?
对于,多次按成不是很熟悉,望指点。。。
private void btnStart_Click(object sender, EventArgs e)
{
Init();//此方法耗时较长
this.btnStart.Enabled = false;
while (true)
{
Thread newThread = new Thread(new ThreadStart(doSomeThing));
//设置为单元线程
newThread.SetApartmentState(ApartmentState.STA);
newThread.Start();
Application.DoEvents();
Thread.Sleep(20000);
}
}
private void doSomeThing()
{
StartImage();//此方法耗时较长
Invoke(new myDelegate(StartImage));
}
[最优解释]
本帖最后由 bdmh 于 2012-11-27 15:17:15 编辑 while (true),不死才怪,他在主线程中,把while (true)放到子线程中去
[其他解释]
死在Thread.Sleep(20000);里,既然你用了Application.DoEvents()也可以不用多线程,
你把Thread.Sleep(20000)改为Thread.Sleep(500)就不会假死,
while (true) { StartImage(); Application.DoEvents(); Thread.Sleep(500); }
[其他解释]
用包装好的BackgroundWork,处理下就够了
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
this.Invoke(new MethodInvoker(delegate()
{
//更新UI,提示正在执行后台操作
this.lable1.Text = "正在计算...";
}));
//长时间处理的代码
Thread.Sleep(100000);
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
this.Invoke(new MethodInvoker(delegate()
{
//更新UI,提示正在执行后台操作
this.lable1.Text = "计算完成^_^";
}));
}
[其他解释]
这一句为了发帖说明加上去的
[其他解释]
我程序需要10分钟或者5分钟执行一次StartImage 方法,这个不确定,应该是配置的,我这只是写了数字。。
[其他解释]
能不能详细说一下?谢谢