Microsoft announced the Visual Studio Async CTP today (October 28, 2010) that introduces the async and await keywords into C#/VB for asynchronous method execution.
First I thought that the compiler translates the keywords into the creation of a thread but according to the white paper and Anders Hejlsberg’s PDC presentation (at 31:00) the asynchronous operation happens completely on the main thread.
How can I have an operation executed in parallel on the same thread? How is it technically possible and to what is the feature actually translated in IL?
It works similarly to the
yield returnkeyword in C# 2.0.An asynchronous method is not actually an ordinary sequential method. It is compiled into a state machine (an object) with some state (local variables are turned into fields of the object). Each block of code between two uses of
awaitis one “step” of the state machine.This means that when the method starts, it just runs the first step and then the state machine returns and schedules some work to be done – when the work is done, it will run the next step of the state machine. For example this code:
Would be translated to something like:
The important part is that it just uses the
SetContinuationmethod to specify that when the operation completes, it should call theStepmethod again (and the method knows that it should run the second bit of the original code using the_statefield). You can easily imagine that theSetContinuationwould be something likebtn.Click += Step, which would run completely on a single thread.The asynchronous programming model in C# is very close to F# asynchronous workflows (in fact, it is essentially the same thing, aside from some technical details), and writing reactive single-threaded GUI applications using
asyncis quite an interesting area – at least I think so – see for example this article (maybe I should write a C# version now :-)).The translation is similar to iterators (and
yield return) and in fact, it was possible to use iterators to implement asynchronous programming in C# earlier. I wrote an article about that a while ago – and I think it can still give you some insight on how the translation works.