does async/await method run in the same thread as caller?

梦想与她 提交于 2019-12-20 03:33:11

问题


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?


回答1:


Have I missed something?

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.

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.

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.



来源:https://stackoverflow.com/questions/21390186/does-async-await-method-run-in-the-same-thread-as-caller

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!