The right way to get CoreDispatcher in the Windows Store app

I am creating an application for the Windows Store and I have the code that needs to be sent to the UI thread.

For this, I would like to get CoreDispatcher and use it to publish code.

There seem to be several ways to do this:

// 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?

+76
c # windows-store-apps windows-runtime async-await dispatcher
May 10 '13 at 7:24
source share
4 answers

This is the preferred way:

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

The advantage is that it gets the core CoreApplicationView and is therefore always available. More details here .

There are two alternatives that you could use.

First alternative

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

This gets the active view for the application, but it will give you a null value if no views have been activated. More details here .

Second alternative

 Window.Current.Dispatcher 

This solution will not work if it is called from another thread, as it returns null instead of the interface manager. More details here .

+128
Aug 28 '13 at 10:25
source share

For those using C ++ / CX

 Windows::ApplicationModel::Core::CoreApplication::MainView->CoreWindow->Dispatcher->RunAsync( CoreDispatcherPriority::Normal, ref new Windows::UI::Core::DispatchedHandler([this]() { // do stuff })); 
+12
Jun 07 '16 at 18:29
source share
 await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync( CoreDispatcherPriority.Normal, () => { // your code should be here}); 
+3
Jun 08 '15 at 23:10
source share

Actually, I would suggest something in the line of this:

 return (Window.Current == null) ? CoreApplication.MainView.CoreWindow.Dispatcher : CoreApplication.GetCurrentView().CoreWindow.Dispatcher 

Thus, if you have openend another View / Window, you will not get Dispatchers confused ...

This little pearl checks to see if there is even a Window. If not, use the MainView Manager. If you have a view, use this dispatcher.

0
Jul 11 '17 at 14:01
source share



All Articles