Thread control flow in async .NET Console program [duplicate]

不羁岁月 提交于 2019-12-02 00:44:50
Jeroen van Langen

In short, When the SynchronizationContext.Current not is set, (which is the case on a console application). The await response is invoked on the ThreadPool.

On a Winforms/WPF a SynchronizationContext is implemented to queue the response to either the winforms controlToSendTo.BeginInvoke(); or the WPF Dispatcher.BeginInvoke();.

Reference:

  • Await, SynchronizationContext, and Console Apps (a blog post by a member of the dev team):

    But there's one common kind of application that doesn't have a SynchronizationContext: console apps. When your console application's Main method is invoked, SynchronizationContext.Current will return null. That means that if you invoke an asynchronous method in your console app, unless you do something special, your asynchronous methods will not have thread affinity: the continuations within those asynchronous methods could end up running "anywhere."

  • Parallel Computing - It's All About the SynchronizationContext (an article referenced from the official documentation for the SynchronizationContext class):

    By default, all threads in console applications and Windows Services only have the default SynchronizationContext.

    ...

    Figure 4 Summary of SynchronizationContext Implementations
    ...

    ╔═════════╦═══════════╦════════════╦════════════╦══════════╦══════════╗
    ║         ║ Specific  ║ Exclusive  ║ Ordered    ║ Send May ║ Post May ║
    ║         ║ Thread    ║ (Delegates ║ (Delegates ║ Invoke   ║ Invoke   ║
    ║         ║ Used to   ║ Execute    ║ Execute    ║ Delegate ║ Delegate ║
    ║         ║ Execute   ║ One at     ║ in Queue   ║ Directly ║ Directly ║
    ║         ║ Delegates ║ a Time)    ║ Order)     ║          ║          ║
    ╠═════════╬═══════════╬════════════╬════════════╬══════════╬══════════╣
    ║ ...     ║           ║            ║            ║          ║          ║
    ╠═════════╬═══════════╬════════════╬════════════╬══════════╬══════════╣
    ║ Default ║ No        ║ No         ║ No         ║ Always   ║ Never    ║
    ╚═════════╩═══════════╩════════════╩════════════╩══════════╩══════════╝
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!