4

我正在编写一个 Windows 10 通用应用程序。我需要在 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()
        });
    }

我将如何做到这一点?

4

1 回答 1

6

只需在之后调用回调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 线程调用:它会导致你的应用程序死锁。从一个工作线程来说,在某些情况下是可以接受的,因为没有同步上下文,所以不能死锁。

于 2015-12-07T15:20:33.857 回答