Run code on UI thread in WinRT

ofer picture ofer · May 14, 2012 · Viewed 59.9k times · Source

How can I run code on the UI thread in WinRT (Windows 8 Metro)?

The Invoke method does not exist.

Answer

Cœur picture Cœur · Jun 26, 2013

It's easier to directly get the CoreWindow from the non-UI thread. The following code will work everywhere, even when GetForCurrentThread() or Window.Current returns null.

CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
    <lambda for your code which should run on the UI thread>);

for example:

CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
    () =>
    {
        // Your UI update code goes here!
    });

You'll need to reference Windows.ApplicationModel.Core namespace:

using Windows.ApplicationModel.Core;