Better async programming in .Net

Better support for asynchronous programming was announced for C# 5.0 and a preview version has been released.
It adds two new keywords, async and await, which enable the following programming model:

async Task<SomeResult> MyMethodAsync() {

  SomeResult result = ...

  try {

    foreach (...) {

      var data = await SomeAsyncMethod();

      result.Add(data);

    }

  } catch (...)

  return result;

}

Task<Data> SomeAsyncMethod() {...}

This seems a very elegant solution, as the code reflects the desired execution sequence without unnatural callback methods. In particular, it greatly simplifies exception handling and other call structures (loops and such). Also, it builds upon the Task class introduced in NetFx and later officially included into C# 4.0.

Under the covers, the method above get compiled with tricks similar to iterators: capturing the local variables of the method into an object to maintain state when the method yields control away, and using a state machine to model the structure of the method and it's various interruption/continuation points.

When the first "await" keyword is reached, the method returns a Task object, holding the promise of a future result.
In the case of iterators, the method would resume after the "yield" statement the next time the GetNext() method would be called again.
But in the case of async methods, the code after "await" executes as a callback of the inner asynchronous operation (SomeAsyncMethod in the example above). Subsequent await statements are also translated into callbacks.
When a "return" statement is reached, as the end of this chain of callbacks, the Task which was handed to the caller completes and finally delivers its result.

As it stands, you can only use "await" in methods marked with "async". But I don't understand why the "async" keyword is needed, as it seems that the compiler could recognize such methods by the presence of the "await" keyword in the body of the method. (Update: here's why)






Get Microsoft Silverlight

See the Async page on MSDN for more videos and a whitepaper on this feature.

Posted by Julien on October 28, 2010. Permalink
Comments
comments powered by Disqus

Personally, I really do hate the direction, C# is going. More half-baked stuff added in each subsequent version.

Posted by: Uwe at December 6, 2010 01:47 PM
Trackbacks