1. Async/await
await Task.Delay(5000);
statusLabel.Text = "Work Completed!";
This won’t throw exception because
- When we
await, the method pauses, but the UI thread is free to process events. - After the await, the continuation automatically resumes on the original calling thread, which in a WinForms/WPF app is the UI thread.
- That’s why we can update UI controls directly
2. Raw worker thread
Thread worker = new Thread(() =>
{
Thread.Sleep(5000);
statusLabel.Text = "Work Completed!"; //❌
});
worker.Start();
- The worker thread runs completely separate from the UI thread.
- Attempting to update a control directly causes an exception.
- We must marshal the call to the UI thread:
statusLabel.Invoke(new Action(() =>
{
statusLabel.Text = "Work Completed!";
}));
So this is just to show the advantage of using asynchronous programming with async/await/Task which was introduced in 2012 alongside .NET Framework 4.5.
Before .Net Framework 4.5 we have to do the nasty thing you see with Invoke.
