开发者

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

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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜