How can I run code on the UI thread in WinRT (Windows 8 Metro)?
The Invoke
method does not exist.
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With