How does C# 5 async return to main thread?

陌路散爱 提交于 2019-12-03 17:37:19

The callback is attached to the task, using the current task scheduler (that's "current" at the time of awaiting, not current at the time of completion). For a UI thread, the current task scheduler will schedule the callback to be executed within the UI thread... for a thread pool thread, the scheduler will allow it to be executed on any thread pool thread, etc.

Assuming you're awaiting a Task<T>, it's effectively calling Task<T>.ContinueWith(continuationAction, scheduler).

You can await anything with the right methods available, but how BeginAwait schedules the continuation is implementation-specific. I've only mentioned the task-based one because it's probably the most common one. The compiler itself doesn't specify this at all - it assumes that the libraries will do the right thing. All the compiler does is translate "the rest of the method" into a continuation, and pass that into BeginAwait.

The compiler compiles your code differently and splits it so that code after await becomes a callback. There's a detailed explanation to a certain extent here: http://evolpin.wordpress.com/2011/05/02/c-5-await-and-async-in-asp-net/

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