6

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.

prolink007
  • 33,872
  • 24
  • 117
  • 185
Nilzor
  • 18,082
  • 22
  • 100
  • 167

2 Answers2

16

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());
Oleg
  • 422
  • 3
  • 13
  • 2
    I guess this works, but it would be nice if anyone knew of a solution not requiring a third party library. – Nilzor Aug 16 '12 at 11:04
  • Thanks a lot. I guess the Window.Current.Dispatcher.HasThreadAccess bool is the key. – Nilzor Aug 17 '12 at 08:00
3

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();
                });
            }
Calanus
  • 25,619
  • 25
  • 85
  • 120