异步/等待方法是否在与调用方相同的线程中运行? [英] does async/await method run in the same thread as caller?

查看:78
本文介绍了异步/等待方法是否在与调用方相同的线程中运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读到async/await方法与调用方在同一线程中运行,并且在WPF应用程序中看到了它,但是在控制台应用程序中测试代码时,我发现它在与调用方不同的线程中运行. 我错过了什么吗?

I have read that async/await methods runs in the same thread as caller and I saw it in a WPF application but while testing a code in console application I see it is running in a different thread than caller. Have I missed something?

推荐答案

我错过了什么吗?

Have I missed something?

排序. await线程一无所知.如果存在,它将导致await关键字之后的代码(默认情况下)在与调用方相同的SynchronizationContext中运行.

Sort of. await doesn't know anything about threads. It causes the code after the await keyword (by default) to run in the same SynchronizationContext as the caller, if it exists.

对于WPF应用程序,当前的SynchronizationContext被设置为封送回UI线程的调用,这意味着它将最终出现在UI线程上. (在Windows窗体中也是如此).在控制台应用程序中,没有SynchronizationContext,因此它无法回发到该上下文,这意味着您最终将进入ThreadPool线程.

In the case of a WPF Application, the current SynchronizationContext is setup to marshal the call back to the UI thread, which means it will end up on the UI thread. (The same is true in Windows Forms). In a Console Application, there is no SynchronizationContext, so it can't post back onto that context, which means you'll end up on a ThreadPool thread.

如果要在SynchronizationContext.Current中安装自定义SynchronizationContext,则呼叫将在此处发布.但是,这在控制台应用程序中并不常见,因为它通常需要类似消息循环"之类的内容才能正常工作.

If you were to install a custom SynchronizationContext into SynchronizationContext.Current, the call would post there. This is not common in Console Applications, however, as it typically requires something like a "message loop" to exist to work properly.

这篇关于异步/等待方法是否在与调用方相同的线程中运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆