Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to get the CoreDispatcher in a Windows Store app

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?

like image 420
lysergic-acid Avatar asked May 10 '13 07:05

lysergic-acid


2 Answers

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.

like image 177
MAXE Avatar answered Oct 05 '22 01:10

MAXE


For anyone using C++/CX

Windows::ApplicationModel::Core::CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync(     CoreDispatcherPriority::Normal,     ref new Windows::UI::Core::DispatchedHandler([this]() {     // do stuff })); 
like image 26
Brett Pennings Avatar answered Oct 05 '22 03:10

Brett Pennings