我正在编写一个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()
});
}
我将如何做到这一点?
答案 0 :(得分:5)
只需在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();
}
注意:永远不要从UI线程调用GetResults
:它会导致您的应用死锁。从工作线程来看,在某些情况下可以接受,因为没有同步上下文,所以它不会死锁。