October 20, 2014

Async/Await

Best explanation I have found
Looking underneath the hood
More complicated but diagrammed example here

The “async” keyword tells compiler that the method may return asynchronously, it enables the use of the await keyword. The beginning of an async method is executed just like any other method, it runs synchronously until it hits an “await” (or throws an exception).

The “await” keyword is where things can get asynchronous. Await is like a unary operator: it takes a single argument, an awaitable (an “awaitable” is an asynchronous operation). Await examines that awaitable to see if it has already completed; if the awaitable has already completed, then the method just continues running synchronously just like a regular method.

If “await” sees that the awaitable has NOT completed, then it acts asynchronously. It tells the awaitable to run the remainder of the method when it completes, and then returns from the async method.

Careful with a method that leaves a lot of data on the stack. This data will stay around until the async method is complete, ie all "async" tasks have completed.
private static async void DoSomethingAsync()
{
    var result = await SomeTask(args);
    DoSomethingWithResult(result);    
}

No comments: