The Dispatcher
class is a very common way of accessing the UI thread while we are on another thread.
With WPF 4.5 we have some new methods for synchronous and asynchronous operations, which make this Dispatcher
class more async and await friendly. Another improvement is that Dispatcher.Invoke
and Dispatcher.InvokeAsync
are now able to return a value.
Finally, we also have a new parameter of CancellationToken
type, which provides the obvious capability of being able to cancel dispatched tasks.
In the following steps we will see how to use the Dispatcher
class to dispatch a task that accesses the UI thread.
First open Visual Studio 2012 and create a new project. We will select the WPF Application template from the Visual C# category and name it
WPFDispatcher
.Open the
MainWindow.xaml
view and add a Button Click event, name itbtnDispatcher
and enter1
as the content...