I have seen a lot of discussion out there about why Dispatchers in WPF don’t implement ISynchronizedInvoke.
I don’t have the answer, but I can offer you an extension method I use to simplify the synchronization of all those asynchronous events onto a window thread.
Here is the extension method:
public static class Extensions
{
static public void InvokeIfRequired(this Dispatcher dispatcher, Action action)
{
if (dispatcher.CheckAccess())
{
action();
}
else
{
dispatcher.BeginInvoke(DispatcherPriority.Normal, action);
}
}
}
And you can use it like this:
void task_CompletedEvent(object sender, EventArgs args)
{
// Possibly called from another thread
Dispatcher.InvokeIfRequired(() =>
{
// You can access the UI here, we are in the window thread
});
}