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

前端 未结 1 1763
忘掉有多难
忘掉有多难 2021-01-22 00:58

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

相关标签:
1条回答
  • 2021-01-22 01:25

    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.

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题