Search code examples
c#asynchronousasync-ctpasync-await

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?


Solution

  • 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.