Using the dispatcher
WinUI, like WPF, uses a single-thread model to manage the UI. This means that, in your code, you can interact with the controls included in your window only from the UI thread. Consider, for example, the following code:
Task.Run(() => { //do some heavy work myTextBlock.Text = result; });
By using Task.Run()
, we are forcing the code to be executed on a background thread. However, if you run this snippet, you will get an exception, as shown in the following screenshot:
This is expected, since we're trying to access UI control from a background thread. To manage these scenarios, all the .NET UI platforms use the concept of a dispatcher, which, as the name suggests, is able to dispatch a specific action from a different thread to the UI thread.
In WPF, the dispatcher is implemented...