我如何确定我是否需要派遣UI线程的WinRT /地铁? [英] How do I determine if I need to dispatch to UI thread in WinRT/Metro?

查看:291
本文介绍了我如何确定我是否需要派遣UI线程的WinRT /地铁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在.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光工具包 - <一个href="http://mvvmlight.$c$cplex.com/SourceControl/changeset/view/4be0aa663f97#GalaSoft.MvvmLight/GalaSoft.MvvmLight%20%28NET35%29/Threading/DispatcherHelper.cs">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());

这篇关于我如何确定我是否需要派遣UI线程的WinRT /地铁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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