我正在写一个Windows 10 Universal应用程序.我需要在UI线程上运行一些特定的代码,但是一旦代码完成,我想在首先调用请求的同一个线程上运行一些代码.见下面的例子:
private static async void RunOnUIThread(Action callback) { //<---- Currently NOT on the UI-thread await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { //Do some UI-code that must be run on the UI thread. //When this code finishes: //I want to invoke the callback on the thread that invoked the method RunOnUIThread //callback() //Run this on the thread that first called RunOnUIThread() }); }
我怎么做到这一点?
只需在以下后调用回调await Dispatcher.RunAsync
:
private static async void RunOnUIThread(Action callback) { //<---- Currently NOT on the UI-thread await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { //Do some UI-code that must be run on the UI thread. }); callback(); }
回调函数将在来自线程池的工作线程上调用(但不一定是相同的RunOnUIThread
,但是你可能不需要这样做)
如果你真的想在同一个线程上调用回调,不幸的是它变得有点乱,因为工作线程没有同步上下文(允许你在特定线程上调用代码的机制).所以你必须Dispatcher.RunAsync
同步调用以确保你保持在同一个线程:
private static void RunOnUIThread(Action callback) { //<---- Currently NOT on the UI-thread Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { //Do some UI-code that must be run on the UI thread. }).GetResults(); callback(); }
注意:永远不要GetResults
从UI线程调用:它会导致您的应用程序死锁.从工作线程,在某些情况下可以接受,因为没有同步上下文,所以它不能死锁.