我如何确定我是否需要派遣UI线程的WinRT /地铁?线程、地铁、UI、WinRT

2023-09-04 09:56:21 作者:初识钟情

在.NET中你有 System.Threading.Thread.IsBackground

是否有这个在WinRT中的一些当量/地铁?

Is there some equivalent of this in WinRT/Metro?

我有改变UI特性的方法,我想确定我是否需要派遣执行到UI线程运行。

I have a method which changed UI properties, and I want to determine whether or not I need to dispatch the execution to the UI thread runtime.

推荐答案

嗯,如果你使用 MVVM光工具包 在你的应用程序,你可以使用 CheckBeginInvokeOnUI(动作动作)方法 GalaSoft.MvvmLight.Threading.DispatcherHelper 自动处理这种情况的类。

Well, if you use MVVM Light Toolkit in your app, you can use CheckBeginInvokeOnUI(Action action) method of GalaSoft.MvvmLight.Threading.DispatcherHelper class which handles this situation automatically.

GalaSoft.MvvmLight.Threading.DispatcherHelper.CheckBeginInvokeOnUI(() =>
{
    Gui.Property = SomeNewValue;
});

编辑:

下面code基于 DispatcherHelper 类 MVVM光工具包 - link

The following code is based on DispatcherHelper class of MVVM Light Toolkit - link

但是,如果你不想使用MVVM光(这是pretty的很酷的事情的方式的),你可以尝试这样的事(抱歉,不能如果检查作品,没有Windows 8):

But if you don't want to use MVVM Light (which is pretty cool thing by the way), you can try something like this (sorry, can't check if this works, don't have Windows 8):

var dispatcher = Window.Current.Dispatcher;

if (dispatcher.HasThreadAccess)
    UIUpdateMethod();
else dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => UIUpdateMethod(););

这将是更好的把这个逻辑在不同的班级是这样的:

It would be nicer to put this logic in separate class like this:

using System;
using Windows.UI.Core;
using Windows.UI.Xaml;

namespace MyProject.Threading
{
    public static class DispatcherHelper
    {
        public static CoreDispatcher UIDispatcher { get; private set; }

        public static void CheckBeginInvokeOnUI(Action action)
        {
            if (UIDispatcher.HasThreadAccess)
                action();
            else UIDispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                       () => action());
        }

        static DispatcherHelper()
        {
            if (UIDispatcher != null)
                return;
            else UIDispatcher = Window.Current.Dispatcher;
        }
    }
}

然后你可以使用它像:

Then you can use it like:

DispatherHelper.CheckBeginInvokeOnUI(() => UIUpdateMethod());