本文介绍了为什么Thread.Sleep()会以这种方式运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我编写的简单代码:
This is a simple code that I have written:
private void button1_Click(object sender, EventArgs e)
{
label1.Text = "first";
Thread.Sleep(1000);
label1.Text = "second";
}
但是标签从不显示"first".我使用断点进行了检查,并执行了语句label1.text ="first",但在标签中未显示"first",仅显示了"second".
But the label never displays 'first'. I checked using break point and the statement label1.text="first" gets executed but does not display 'first' in label, only 'second' is displayed.
为什么会这样?
推荐答案
那是因为您让主线程进入睡眠状态.因此,它无法将新文本绘制到标签上.
That is because you let the main thread sleep. Therefore it is unable to paint the new text onto the label.
您可以使用以下方法强制"处理队列中的(绘画)事件:
You can 'force' the handling of the (paint) events in queue by using:
Application.DoEvents();
Thread.Sleep(1000);
然后请阅读此问题使用Application.DoEvents()"
However then please read this question 'Use of Application.DoEvents()'
这篇关于为什么Thread.Sleep()会以这种方式运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!