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>);
On UWP, I was having problem trying to set the Source property of CaptureElement control (that is defined in XAML), it was complaining about being prepared at different thread, even though I was trying to set it from code that was invoked via a Page_Loaded event handler. I ended up using this to work around it:
var UISyncContext = TaskScheduler.FromCurrentSynchronizationContext();
Then start a new Task and on the above UISyncContext.
Task.Factory.StartNew(() => { /* Do your UI stuff here; */}, new System.Threading.CancellationToken(), TaskCreationOptions.PreferFairness, UISyncContext);
Use:
It works for me.
It's easier to directly get the CoreWindow from the non-UI thread. The following code will work everywhere, even when
GetForCurrentThread()
orWindow.Current
returns null.for example:
You'll need to reference
Windows.ApplicationModel.Core
namespace:Use:
From your UI thread, execute:
From your background (non UI thread)
That should work on both CP and later builds.
DispatcherTimer is also an option.
I used it for code that must be run in Xaml-designer (CoreWindow.Dispatcher,... are not available in UWP-designer)
Disclaimer:
I should note that this should be a last-resort option if every other fails.
On UWP, I was having problem trying to set the Source property of CaptureElement control (that is defined in XAML), it was complaining about being prepared at different thread, even though I was trying to set it from code that was invoked via a Page_Loaded event handler. I ended up using this to work around it:
This is a much easier way in my opinion.
Get the TaskScheduler associated with the UI.
Then start a new Task and on the above UISyncContext.