1

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?

Ray Hayes
  • 14,896
  • 8
  • 53
  • 78
Shiridish
  • 4,942
  • 5
  • 33
  • 64

3 Answers3

10

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

Community
  • 1
  • 1
Myrtle
  • 5,761
  • 33
  • 47
2

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.

Femaref
  • 60,705
  • 7
  • 138
  • 176
0

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.

oybcs
  • 327
  • 1
  • 4
  • 14