Run code in user interface thread in WinRT

How to run code in a user interface thread in WinRT (Windows 8 Metro)?

Invoke method does not exist.

+63
multithreading windows-8 windows-runtime dispatcher
May 14 '12 at 7:21
source share
6 answers

It is easier to directly get CoreWindow from a thread other than the UI. The following code will work everywhere, even if GetForCurrentThread() or Window.Current returns null.

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

eg:

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

You will need to reference the Windows.ApplicationModel.Core namespace:

 using Windows.ApplicationModel.Core; 
+73
Jun 26 '13 at 8:32
source share

Using:

From the user interface thread, do:

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

From your background (no UI thread)

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

This should work on both CP and subsequent builds.

+68
May 15, '12 at 5:02
source share

Using:

 this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => Frame.Navigate(typeof(Welcome), this)); 

This works for me.

+8
Sep 14 '12 at 7:32
source share

This is a much simpler way, in my opinion.

Get the TaskScheduler associated with the user interface.

  var UISyncContext = TaskScheduler.FromCurrentSynchronizationContext(); 

Then run a new task and in the above UISyncContext.

  Task.Factory.StartNew(() => { /* Do your UI stuff here; */}, new System.Threading.CancellationToken(), TaskCreationOptions.PreferFairness, UISyncContext); 
+5
Oct 12
source share

DispatcherTimer is also an option.

I used it for code that should be run in a Xaml designer (CoreWindow.Dispatcher, ... not available in a UWP designer)

 var localTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(0) }; localTimer.Tick += (timer, e) => { (timer as DispatcherTimer).Stop(); action(); }; localTimer.Start(); 

Denial of responsibility:
I should note that this should be the last resort option if each other does not work.

0
Nov 28 '16 at 17:39
source share

In UWP, I had a problem setting the Source property of the CaptureElement control (which is defined in XAML), it complained about the preparation in another thread, although I tried to install it from the code that was called through the Page_Loaded event handler. I ended up using this to get around this:

 previewControl.Dispatcher.TryRunAsync(CoreDispatcherPriority.Normal, () => { previewControl.Source = _mediaCapture; }).GetAwaiter().GetResult(); 
0
Aug 24 '17 at 13:49 on
source share



All Articles