Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 混淆了dispatcher和async_C#_Multithreading_Xaml_Asynchronous_Async Await - Fatal编程技术网

C# 混淆了dispatcher和async

C# 混淆了dispatcher和async,c#,multithreading,xaml,asynchronous,async-await,C#,Multithreading,Xaml,Asynchronous,Async Await,我正在制作一个Windows8.1平板电脑应用程序,并且大量使用async关键字。 我对async关键字的理解是,虽然它看起来与程序员是同步的,但不能保证在等待完成时您将在同一线程上运行 在我的代码隐藏文件中,我可以使用Dispatcher在UI线程上运行任何UI更新。我发现的每个示例都表明,在使用“回调”类型场景时,这是一个很好的实践,但在使用异步时,我没有看到提到过它。从我对async的理解来看,似乎每当我想在任何等待调用后更新UI时,我都需要使用dispatcher 我试图通过在下面的代码

我正在制作一个Windows8.1平板电脑应用程序,并且大量使用async关键字。 我对async关键字的理解是,虽然它看起来与程序员是同步的,但不能保证在等待完成时您将在同一线程上运行

在我的代码隐藏文件中,我可以使用Dispatcher在UI线程上运行任何UI更新。我发现的每个示例都表明,在使用“回调”类型场景时,这是一个很好的实践,但在使用异步时,我没有看到提到过它。从我对async的理解来看,似乎每当我想在任何等待调用后更新UI时,我都需要使用dispatcher

我试图通过在下面的代码中表达我的理解来更清楚一些

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,而线程并不重要?如果有人能为我澄清这一点,那就太好了

我对async关键字的理解是,虽然它看起来与程序员是同步的,但不能保证在等待完成时您将在同一线程上运行

不完全是。。。如果启动异步操作的线程具有同步上下文(对于UI线程是如此),则执行将始终在同一线程上继续,除非您明确指定不使用
.ConfigureAwait(false)
捕获同步上下文

如果没有同步上下文,或者没有捕获它,那么执行将在
线程池
线程上继续(除非等待的任务实际上是同步完成的,在这种情况下,您将保持在同一线程上)

下面是您的代码片段和更新的注释:

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
    });
}

虽然在UI情况下是这样,但在一般情况下,
SynchronizationContext
!=线一个显著的例子是ASP.NET,其中
AspNetSynchronizationContext
指的是“请求上下文”。另外,
await
如果没有
SynchronizationContext
(尽管这在实践中并不常见),则将退回到当前的
TaskScheduler