异步/等待方法是否在与调用方相同的线程中运行?
我已经阅读到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.