1

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.

Igor Ševo
  • 5,459
  • 3
  • 35
  • 80
  • So where are you calling the Dispatcher: in `apiCall()`? Maybe you could post a little more code to make it easier – Freggar May 15 '18 at 10:59

1 Answers1

1

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.

Igor Ševo
  • 5,459
  • 3
  • 35
  • 80
Dave Smits
  • 1,871
  • 14
  • 22
  • Can a background task be converted to activate the main app similar to https://learn.microsoft.com/en-us/windows/uwp/launch-resume/convert-app-service-in-process? – Igor Ševo May 15 '18 at 11:26
  • 1
    A background task can run in the same process as the app. this makes it easier to share data between the app and the background process. It also enables to do direct procedure calls. It wont allow to let the background task (code running in the background) start UI. This would be very annoying for the users. Via a background task you can show a toast notification. A toast notification can be interactive and let user already perform actions. When the user click on the notification the UI can start. – Dave Smits May 16 '18 at 07:37