Monday, December 31, 2012

Async – Await



A new asynchronous programming model introduced in C# 5.0. The programming style using (Async Await) would be as similar as like synchronous programming with slight code changes.
There are other asynchronous programming methods before such as like
1)      APM (Asynchronous Programming Model) – Begin Invoke, End Invoke…
2)      EAP (Event Asynchronous Pattern) – Event is raised after the completion of Asynchronous function.
3)      TAP (Task Asynchronous Pattern) – Using Task library that helps to build a wrapper (task) on the actual function. The status of the task can be fetched from the task object.

The next model is using Async – Await introduced in C# 5.0.
Below is a sample code, with traditional synchronous and latest asynchronous methods,
Synchronous
Function which would take some time (5 seconds) and returns a number.
  private Int32 GetNumber()
        {
            Thread.Sleep(5000);
            return 10;
        }
Asynchronous using Async Await.


        private async Task<Int32> GetNumber()
        {
            //statements are executed in synchronous manner, as long as there is
            //no await statement
            int a = 10;

            //when there is an await statment, which means compiler will understand that
            //it has to wait for the result, but since the method is marked as async hence it returns the
            //control to the calling method without blocking
            return await Task.Run(() =>
                 {
                     Thread.Sleep(5000);
                     return 10;
                 });

            //when the above task is completed, it would run  the next statements again in synchronous manner as long
            //as there is no await statement.
            a = 20;
        }

Caller :
  private async void button1_Click(object sender, EventArgs e)
        {
            Int32 result = await GetNumber();
 }

The similar async – await can be used for the delegate methods which are invoked by the task library.
Below is an example, declaring async delegate methods in a task.

Task<Int32> result1 =  Task.Run(async () =>
                    {
                        await Task.Delay(5000);
                        return 10;
             });

Note :
1)      To enable async- await – asynchronous behavior, the method should be declared as async.
2)      Method declared as async, may or may not have a await statement.
3)      If there is no await statement in a sync method, compiler executes like a synchronous method.
4)      To have a await statement, method should be declared as async .
5)      A async method always returns Task or Task<T> or can be void.

Why should a async method return type always have to be Task or Task<T> or void.

When a async method is invoked, compiler would expect that there could be a piece of code which needs to be asynchronous.
Hence when there is a await statement which might be in the middle of the code block with in the method, compiler will execute from there as a separate till the end of the code block.

Creating a task for this is because, since it has to run asynchronously it will goto the caller when an await statement is identified.
So to monitor the code execution from await statement, the return task handle would help to do.
If it is not required to bother about the further execution which would happen hence not required to handle return type and hence can be void.