Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I determine if I need to dispatch to UI thread in WinRT/Metro?

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.

like image 348
Nilzor Avatar asked Aug 16 '12 09:08

Nilzor


2 Answers

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());
like image 130
Oleg Avatar answered Nov 09 '22 21:11

Oleg


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();
                });
            }
like image 44
Calanus Avatar answered Nov 09 '22 21:11

Calanus