async/await 方法是否与调用者在同一线程中运行?

2024-03-16

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? enter image description here


我错过了什么吗?

有点。await什么都不知道threads。它导致后面的代码await关键字(默认)在同一个中运行SynchronizationContext作为调用者(如果存在)。

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

如果您要安装自定义SynchronizationContext into SynchronizationContext.Current,呼叫将发布在那里。然而,这在控制台应用程序中并不常见,因为它通常需要诸如“消息循环”之类的东西才能正常工作。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

async/await 方法是否与调用者在同一线程中运行? 的相关文章

随机推荐