Possible Duplicate:
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";
}
When this code is executed and button is clicked, label1 displays text as only ‘second’ but not ‘first’. I checked using break point, and statement label1.text=”first” is executed but label does not display ‘first’. Why is this so?
Because your code is running on the UI thread.
When your app is running and you’re not clicking on things, the application’s main thread is rushing around, waiting for events, processing Windows messages, and painting the screen. When you click your button, the app stops doing those things, and runs your function instead. While it’s running your method, it can’t paint the screen. Your function sets the label to “First”, blocks the thread for a second, then sets the label to “second”.
When you return, control passes back to the application, which is then free to repaint the form. It repaints it using the “second” label. The message loop never had chance to paint it with the “first” label.