The code above will sleep the UI thread, so what essentially happens is this:
- Request that label text be set to "Wrong Password!" (not updated till next UI thread tick)
- Sleep for 5 seconds
- Request that label text be set to ""
- UI thread ticks, label is set to ""
To work around this do something like:
Label1.Text = "Wrong Password!";
// start a new background thread
new Thread(new ThreadStart(() =>
{
Thread.Sleep(5000);
// interacting with Control properties must be done on the UI thread
// use the Dispatcher to queue some code up to be run on the UI thread
Dispatcher.BeginInvoke(() =>
{
Label1.Text = " ";
});
})).Start();
This will:
- Request that the label text be set to "Wrong Password!"
- Start a different thread that sleeps for 5000ms
- In the meanwhile the UI Thread continues to execute so the Label gets updated to "Wrong Password!"
- 5000ms passes and the background requests that the label text be cleared
- the UI thread ticks and updates the label