What is 'await' looking for !

1:47 AM Shashank Tiwary 0 Comments

The way of running asynchronous operation from C# 5.0 is now has dramatic changes. Specifically there are two new operators async and await introduce by C# 5.0 language to support linear asynchronous programming model.

async

operator use as a modifier to specify that a method, lambda expression, or anonymous method is asynchronous.If you use this modifier on a method or expression, it's referred to as an asynchronous method.

await

operator is applied to a task in an asynchronous method to suspend the execution of the method until the awaited task completes. The task represents ongoing work.

We are going to look into the internals of how await operator works,
C# code uses await operator,
public async void DoSomething()
{
    string result = await obj.GetResultAsync(); // return immediately to calling code
    Console.WriteLine(result); // execution continue from here once above work completed 
}
A pseudo code generated by compiler is give below, When an await operator encounter by compiler.
public async void DoSomething()
{
    // obj - any object that have GetAwaiter method with appropriate return type
    var temp = obj.GetAwaiter(); 
    if (!temp.IsCompleted)
    {
        SAVE_STATE()
        temp.OnCompleted(&cont);
        return;
        cont:
        RESTORE_STATE()
        result = temp.GetResult();
        Console.WriteLine(result); // code below await expression
    }
}
snippet taken from (http://stackoverflow.com/questions/12661348/custom-awaitables-for-dummies)

Here program try to get the awaiter instance from the asynchronous method. This instance temp has an IsCompleted boolean property member which is use to determine if asynchronous task execution completes. If it return false the program store the current machine state and inject an Action (&cont) delegate by using OnCompleted() method of the awaiter instance. Note that this method is part of INotifyCompletion interface. Once the blocking operation execution completes program restore the machine state and get output result by calling GetResult() on awaiter instance. Further program continue below the await statement where its left control.

Condition that compiler check when we use await operator

  1. It check if the return type of await expression does have GetAwaiter() method. This method can also be a extension method for the instance type.
  2. GetAwaiter() must return type that have boolean type property IsCompleted.
  3. Return type of GetAwaiter() must implement INotifyCompletion interface.
  4. Return type of GetAwaiter() must have GetResult() method that return instance of expected type by await expression

0 comments: