You should basically never be sleeping in the UI thread...ever...for exactly the reason your question demonstrates.
You just want to execute some code in 1 second. There are two effective ways at doing this:
1) You can use a Timer
. By using the timer in the Forms
namespace you can ensure that it's Tick
event fires in the UI thread, and you don't need to do anything special to interact with UI elements.
private void Form1_Load(object sender, EventArgs e)
{
label1.Text = "Loading . . .";
var timer = new System.Windows.Forms.Timer();
timer.Interval = 1000;
timer.Tick += (s, args) =>
{
label1.Text = "Done!";
};
timer.Start();
}
As you can see, this does take a bit more code than is ideal, but it still works.
2) If you have .NET 4.5 and C# 5.0 you can use tasks with await
to make this really slick and easy:
private async void Form1_Load(object sender, EventArgs e)
{
label1.Text = "Loading . . .";
await Task.Delay(1000); //wait 1 second, but don't block the UI thread.
label1.Text = "Done!";
}