简体   繁体   English

为什么 Thread.Sleep() 会这样?

[英]Why does Thread.Sleep() behave in this way?

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";
}

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.我使用断点检查并且语句 label1.text="first" 被执行但没有在标签中显示 'first',只显示 'second'。

Why is this so?为什么会这样?

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);

However then please read this question 'Use of Application.DoEvents()'但是,请阅读问题“Application.DoEvents() 的使用”

The moment Thread.Sleep is executed, the UI Thread is sleeping.执行Thread.Sleep的那一刻,UI 线程正在休眠。 As such, the code responsible for updating your UI isn't executed (it can be executed as early as your button1_Click method has returned) and you don't see the result.因此,不会执行负责更新 UI 的代码(它可以在button1_Click方法返回时执行)并且您看不到结果。

From what I've learned, the compiler choses which line is best to compile first.据我所知,编译器会选择最先编译哪一行。 So if you would comment label1.Text = "second" it should display "first" in your label after the 1 second delay.因此,如果您要评论 label1.Text = "second" 它应该在 1 秒延迟后在您的标签中显示“first”。 You can prove that by doing this:你可以通过这样做来证明:

private void button1_Click(object sender, EventArgs e)
{
    label1.Text = "first";
    Thread.Sleep(1000);
    if (label1.Text == "first")
    {
        label1.Text = "second";
    }
}

and it will still display "second" because label1.Text is set to "first" but too short, because it happens after the sleep thats why you can't see it.它仍然会显示“second”,因为 label1.Text 设置为“first”但太短,因为它发生在睡眠之后,这就是为什么你看不到它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM