问题描述
我尝试用Thread.Sleep()
进行实验.我用一个按钮创建了基本的Windows Forms应用程序.
I try to experiment with Thread.Sleep()
. I created basic Windows Forms application with one button.
private void button1_Click(object sender, EventArgs e)
{
Thread thread1 = new Thread(DoStuff);
thread1.Start();
for (int i = 0; i < 100000; i++)
{
Thread.Sleep(500);
button1.Text +=".";
}
}
public void DoStuff()
{
//DoStuff
}
当我单击我的按钮时,DoStuff
方法可以正常工作,但是GUI冻结并且什么也没有发生.有人可以解释一下为什么吗?
When I click my button the DoStuff
method works fine, but the GUI freezes and nothing happens. Can someone explain me why?
推荐答案
要使UI保持活动状态,您需要主UI线程为其消息泵提供服务.它只能在不处理UI事件时执行此操作.在您的情况下,该功能
To keep the UI active, you need for the main UI thread to service its message pump. It can only do that when it is not handling UI events. In your case the function
private void button1_Click(object sender, EventArgs e)
{
Thread thread1 = new Thread(DoStuff);
thread1.Start();
for (int i = 0; i < 100000; i++)
{
Thread.Sleep(500);
button1.Text +=".";
}
}
不会在100000*500
毫秒内返回.在执行此事件处理程序时,UI线程正忙.它正在执行此事件处理程序.因此,它不能为消息泵提供服务.因此,您的应用程序的UI冻结了.
does not return for around 100000*500
milliseconds. While this event handler is executing, the UI thread is busy. It is executing this event handler. As such it is not able to service the message pump. Hence your application's UI freezes.
这篇关于为什么Thread.Sleep()冻结表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!