How does the new async/await feature in C# 5 integrate with the message loop?

邮差的信 提交于 2019-12-23 07:57:14

问题


I've not had chance to check out the CTP of the new C# async/await feature, but here's something I was wondering:

How does it integrate with the message loop? I assume that in a standard Windows application (Winforms, WPF) the continuations are called by sending messages to the application's message loop, using a Dispatcher or similar?

What if I'm not using a standard windows message loop? For example in a GTK# application or in a console application (if indeed this feature could be of use at all in a console application).

I've searched the internet for information about this but to no avail. Can anyone explain?


回答1:


It uses System.Threading.SynchronizationContext.Current. Both WPF and Winforms install their own version of SynchronizationContext. Which use their message loop to marshal the call from a worker thread back to the main UI thread. Respectively with Dispatcher.Begin/Invoke and Control.Begin/Invoke().

Getting this done in a Console mode app is not easy, its main thread doesn't have a well defined 'idle' state that would allow injecting marshaled method calls in a safe manner that avoids re-entrancy headaches. You could certainly add it but you'll be re-inventing the message loop doing so.




回答2:


It all comes down to what the "awaiter" does with the continuation it's passed.

The implementation for Task<T> in the BCL will use the current synchronization context (unless you ask it not to using ConfigureAwait) - which means in WPF/SilverLight it'll use the dispatcher; in Windows Forms it'll use something like Control.BeginInvoke, and in a thread-pool thread it'll just keep run on any thread pool thread. Note that it's your current context at the point of the await expression which is important, as that's what the task will capture for the continuation to run on.

The linked blog post (by Mads Torgersen) does a great job of explaining how it all works under the hood, and I have a series of blog posts which you may find useful too.



来源:https://stackoverflow.com/questions/7747063/how-does-the-new-async-await-feature-in-c-sharp-5-integrate-with-the-message-loo

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