I need to call a method that requires the call be made from the UI thread. My code is executing as a background task (I am using a Windows Runtime Component in UWP and running a background task every 15 minutes).
I would like to call this method from the background task's Run()
method.
The problem is, if the application is not open, the Window.Current
is null
, so I cannot use the Dispatcher
. I tried variations from Correct way to get the CoreDispatcher in a Windows Store app, Run code on UI thread in WinRT and Be two places at once using multiple windows (instantiating a new view), but they all fail with either This method must be called on an UI thread.
or The main windows has not been created.
I also tried the following.
Thread t = new Thread(() => apiCall());
t.SetApartmentState(ApartmentState.STA);
t.Start();
t.Join();
And the following, using a Dispatcher
.
CoreApplicationView newView = CoreApplication.CreateNewView();
await newView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => apiCall());
Both approaches fail with the above errors, respectively.
A background task can't start a UI. You can show a toast notification to let the user open the app via a toast notification.