异步/等待方法是否在与调用方相同的线程中运行?

编程入门 行业动态 更新时间:2024-10-23 15:19:19
本文介绍了异步/等待方法是否在与调用方相同的线程中运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经阅读到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.

更多推荐

异步/等待方法是否在与调用方相同的线程中运行?

本文发布于:2023-11-10 02:17:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574068.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:在与   线程   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!