Shiridish
Shiridish

Reputation: 4962

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.

Why is this so?

Upvotes: 1

Views: 1216

Answers (3)

oybcs
oybcs

Reputation: 327

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. 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.

Upvotes: 0

Myrtle
Myrtle

Reputation: 5851

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()'

Upvotes: 10

Femaref
Femaref

Reputation: 61497

The moment Thread.Sleep is executed, the UI Thread is sleeping. 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.

Upvotes: 2

Related Questions