Going Beyond async and await On WinRT
One of the goals of the new Windows Runtime (WinRT) is to enable better support for developers to utilize asynchronous programming. Asynchronous operations allow a program to maintain responsiveness even while other operations (such as file I/O or network communication) have yet to complete. This responsiveness is helpful to most user applications, including touch-based interfaces where the user expects immediate feedback to their gestures.
To that end, the “await/async” keywords are used by C# and Visual Basic programmers to enable the use of asynchronous operations without suffering extended complications to their program's control flow. Programs following the async API call can rely on the compiler to automatically switch the context to its original state when the call was made. Microsoft's Stephen Toub has recently explored how this process works in greater detail.
The compiler internally rewrites a method marked by async to use a state machine for its implementation. When a programmer marks a statement with the “await” keyword, the compiler is able to inserts markers that allows it to know where it can suspend and resume the method's execution without blocking.
As Toub observes:
When you await an asynchronous operation that’s not yet completed, the compiler’s generated code ensures that all of the state associated with the method (e.g. local variables) is packaged up and preserved on the heap. Then the function returns to the caller, allowing the thread on which it was running to do other work. When the awaited asynchronous operation later completes, the method’s execution resumes using the preserved state.
Toub goes on to discuss situations where the programmer may seek greater control that what is provided by “await”. In this case, the “AsTask” method may be needed to provide support for progress reporting, or to support multiple continuations.
Iordanis Giannakakis, Savvas Dalkitsis Aug 28, 2015