Correct way to get the CoreDispatcher in a Windows Store app

lysergic-acid picture lysergic-acid · May 10, 2013 · Viewed 40.7k times · Source

I'm building a Windows Store app, and I have some code that needs to be posted to the UI thread.

For that, i'd like to retrieve the CoreDispatcher and use it to post the code.

It seems that there are a few ways to do so:

// First way
Windows.ApplicationModel.Core.CoreApplication.GetCurrentView().CoreWindow.Dispatcher;

// Second way
Window.Current.Dispatcher;

I wonder which one is correct? or if both are equivalent?

Answer

MAXE picture MAXE · Aug 28, 2013

This is the preferred way:

Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
    // Your UI update code goes here!
});

The advantage this has is that it gets the main CoreApplicationView and so is always available. More details here.

There are two alternatives which you could use.

First alternative

Windows.ApplicationModel.Core.CoreApplication.GetCurrentView().CoreWindow.Dispatcher

This gets the active view for the app, but this will give you null, if no views has been activated. More details here.

Second alternative

Window.Current.Dispatcher

This solution will not work when it's called from another thread as it returns null instead of the UI Dispatcher. More details here.