Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...