在UWP后台任务中实例化UI线程

时间:2018-05-15 10:52:21

标签: c# uwp background ui-thread background-task

我需要调用一个需要从UI线程调用的方法。我的代码作为后台任务执行(我在UWP中使用Windows运行时组件并每15分钟运行一次后台任务)。

我想从后台任务的Run()方法中调用此方法。

问题是,如果应用程序未打开,则Window.Currentnull,因此我无法使用Dispatcher。我尝试了Correct way to get the CoreDispatcher in a Windows Store appRun code on UI thread in WinRTBe two places at once using multiple windows的变体(实例化新视图),但它们都失败了This method must be called on an UI thread.The main windows has not been created.

我也尝试了以下内容。

Thread t = new Thread(() => apiCall());
t.SetApartmentState(ApartmentState.STA);
t.Start();
t.Join();

以下,使用Dispatcher

CoreApplicationView newView = CoreApplication.CreateNewView();
await newView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => apiCall());

两种方法分别因上述错误而失败。

2 个答案:

答案 0 :(得分:0)

后台任务无法启动UI。您可以显示Toast通知,让用户通过Toast通知打开应用程序。

答案 1 :(得分:0)

此答案可能是您要寻找的:

“通常,让UI线程调用后台操作比让后台操作更新UI线程要容易得多。

因此,我建议您使用DispatcherTimer,然后完全不需要使用Dispatcher。”此处:

Updating ObservableCollection from non UI thread