Using Thread.Sleep
is a blocking call, which means the UI thread is suspended, so the UI freezes.
Suspends the current thread for the specified amount of time.
I guess you call your method in a button event handler. What you can do is add the async
keyword to the event handler method and replace the call to Sleep
with Task.Delay
and await it.
private async void OnClick(object sender, RoutedEventArgs e)
{
labelStatus.Content = "Sending email... ";
labelStatus.Foreground = Brushes.Aqua;
await Task.Delay(3000);
labelStatus.Foreground = Brushes.Pink;
}
This way, the UI thread will not be blocked and the Foreground
will be set to Pink
, after the delay expires.
However, this is not the right approach either. Sending an email or doing other kinds of operations can vary in time, as there are differences in bandwidth, latency or just less resources. You cannot and should not depend on a fixed timespan to wait and hope that an operation is completed. Instead use e.g. the async/await pattern to make your operation run asnychronously and return when it is really completed, like the delay above. This will keep your UI responsive, regardless of whether the operation completed earlier or later.