对dispatcher和async感到困惑

本文关键字:async dispatcher | 更新日期: 2023-09-27 18:04:23

我正在制作一个windows 8.1平板电脑应用程序,并且大量使用async关键字。我对async关键字的理解是,虽然它对程序员来说似乎是同步的,但不能保证当你的await结束时,你将运行在同一个线程上。

在我的代码文件中,我使用Dispatcher在UI线程上运行任何UI更新。我发现的每个例子都表明,当使用"回调"类型场景时,这是一个很好的实践,但我没有看到在使用async时提到它。从我对async的理解来看,似乎每当我想在任何await调用之后更新UI时,我都需要使用调度程序。

我试着把我的理解写在下面的代码里。

private void SomeEventHandler(object sender, RoutedEventArgs e)
{
    UpdateUI(); //This should run in my UI thread
    await Foo(); //When Foo returns I have no guarantee that I am in the same thread
    UpdateUI(); //This could potentially give me an error
    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
    {
        UpdateUI(); //This will run in the UI thread
    });
}

我只需要访问UIContext和线程不重要?如果有人能给我解释一下就太好了。

对dispatcher和async感到困惑

我对async关键字的理解是,虽然它对程序员来说是同步的,但不能保证当你的await结束时你将运行在同一个线程上。

不是……如果启动异步操作的线程有一个同步上下文(对于UI线程是这样),执行将始终在同一个线程上恢复,除非您明确指定不使用.ConfigureAwait(false)捕获同步上下文。

如果没有同步上下文,或者没有捕获同步上下文,那么执行将在ThreadPool线程上恢复(除非等待的任务实际上是同步完成的,在这种情况下,您将留在同一个线程上)。

所以,这是你的代码片段更新注释:
private void SomeEventHandler(object sender, RoutedEventArgs e)
{
    UpdateUI(); //This should run in my UI thread
    await Foo(); //When Foo returns I am still in the UI thread
    UpdateUI(); //This will work fine, as I'm still in the UI thread
    // This is useless, since I'm already in the UI thread ;-)
    await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
    {
        UpdateUI(); //This will run in the UI thread
    });
}