How do I determine if I need to dispatch to UI thr

2019-02-22 09:52发布

问题:

In .NET you have System.Threading.Thread.IsBackground.

Is there some equivalent of this in WinRT/Metro?

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.

回答1:

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



Edit:

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


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());


回答2:

You can access the main ui thread through CoreApplication.Window, e.g.

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