Sunday 9 March 2014

async - await idiom

async-await idiom has been introduced in C# 5.0 and it is basically a syntactic sugar for implementation of task's continuations.

Here are some interesting excerpts from the article "Easier Asynchronous Programming with the New Visual Studio Async CTP" by Eric Lippert, which was published in MSDN Magazine in October 2011:

The work that must come after a particular task is finished is called the continuation of the task.

An await expression (...) means “evaluate this expression to obtain an object representing work that will in the future produce a result. Sign up the remainder of the current method as the callback associated
with the continuation of that task. Once the task is produced and the callback is signed up, immediately return control to my caller.”

Every time an await is encountered, the currently executing method signs up the rest of the method as the thing to do when the current task is complete, and then immediately returns. Somehow each task will complete itself—either by being scheduled to run as an event on the current thread, or because it used an I/O completion thread or worker thread—and will then cause its continuation to “pick up where it left off ” in executing the rest of the method.

Note that the method is now marked with the new async keyword; this is simply an indicator to the compiler that lets it know that in the context of this method, the keyword await is to be treated as a point where the workflow returns control to its caller and picks up again when the associated task is finished.


Asynchronous Programming with Async and Await (MSDN)
async (C# Reference)(MSDN)
await (C# Reference)(MSDN)

Asynchrony in C# 5, Part One (Eric Lippert's blog)

Whenever a task is "awaited", the remainder of the current method is signed up as a continuation of the task, and then control immediately returns to the caller. When the task completes, the continuation is invoked and the method starts up where it was before.

Asynchronous Programming in C# 5.0 part two: Whence await? (Eric Lippert's blog)
Async articles from John Skeet's blog
Async/Await FAQ
What is thread doing after returning from async point? (SO)
What happens to an `awaiting` thread in C# Async CTP?
C# Async Await Cheatsheet