Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run code on UI thread in WinRT

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

The Invoke method does not exist.

like image 201
ofer Avatar asked May 14 '12 07:05

ofer


2 Answers

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;
like image 159
Cœur Avatar answered Oct 31 '22 06:10

Cœur


Use:

From your UI thread, execute:

var dispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher;

From your background (non UI thread)

dispatcher.RunAsync(DispatcherPriority.Normal, 
    <lambda for your code which should run on the UI thread>);

That should work on both CP and later builds.

like image 26
ReinstateMonica Larry Osterman Avatar answered Oct 31 '22 05:10

ReinstateMonica Larry Osterman