如何确定我是否需要派遣到UI线程的WinRT /地铁?(How do I determine if

2019-06-27 02:17发布

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

有没有在WinRT中/地铁的这一些相同呢?

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

Answer 1:

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

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



编辑:

下面的代码是基于DispatcherHelperMVVM光工具包 - 链接


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

var dispatcher = Window.Current.Dispatcher;

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


这将是更好的把这个逻辑在这样单独的类:

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;
        }
    }
}


然后你可以使用它像:

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


Answer 2:

您可以通过CoreApplication.Window,例如访问主UI线程

 if (CoreApplication.MainView.CoreWindow.Dispatcher.HasThreadAccess)
            {
                DoStuff();
            }
            else
            {
                await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    DoStuff();
                });
            }


文章来源: How do I determine if I need to dispatch to UI thread in WinRT/Metro?