在 Windows Store 应用程序中获取 CoreDispatcher 的正确方法 [英] Correct way to get the CoreDispatcher in a Windows Store app

查看:21
本文介绍了在 Windows Store 应用程序中获取 CoreDispatcher 的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个 Windows 应用商店应用,我有一些代码需要发布到 UI 线程.

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

为此,我想检索 CoreDispatcher 并使用它来发布代码.

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?

推荐答案

这是首选方式:

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

这样做的好处是它获得了主要的 CoreApplicationView,因此始终可用.更多详情此处.

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.

第一个选择

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

这会获得应用的活动视图,但如果没有视图被激活,这会给你null.更多详情此处.

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

第二种选择

Window.Current.Dispatcher

当它从另一个线程调用时,此解决方案将不起作用,因为它返回 null 而不是 UI 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.

这篇关于在 Windows Store 应用程序中获取 CoreDispatcher 的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆