Working with the UI thread
In Chapter 3, The Windows App SDK for a WPF Developer, you already met the Dispatcher
class. It's a special class provided by the XAML framework that you can use to dispatch a task on the UI thread. Since every WinUI application has a single UI thread, Dispatcher
becomes especially important when you are executing some code on a background thread but then, at some point, you have to interact with a UI control. Without using the Dispatcher
class, the operation would raise an exception, since you can't update the UI from a different thread than the UI one.
UWP exposes a Dispatcher
class on every page, which belongs to the Windows.UI.Core.CoreDispatcher
namespace. Here is an example of how to use it:
await Dispatcher.RunAsync(Windows.UI.Core. CoreDispatcherPriority.Normal, () => { txtHeader.Text = "This is a header"; });
Actions on the UI thread are dispatched using the RunAsync()
method, which...