Sunday 4 August 2013

Asynchronous programming with Async and Await

Let we see the simple implementation of async and await opertor in C# code.






1. Always async should be mention in method after access specifier.
2. Method name should be end in async.
3. Return type of async method be in void, Task, Task<T>

                The first thing is to know is that any method that you put async in front of is an asynchronous method, which means it can be started and stopped rather than just run from first to last instruction. We could create a new method and mark is as asynchronous but to keep the example as much like the synchronous case described above we can simply change the Click event handler into an asynchronous method:

private async void button1_Click(object sender, RoutedEventArgs e)
{
 
label1..Text = "Started";
 DoWork();
 label2.Text = "Finished";
}

private int DoWork()
{
 return 1+2;
}

Now the compiler will say a message as Asynchronous method with not Await, make to run the method in synchronous way, So i have added await keyword in calling a method.

private async void button1_Click(object sender, RoutedEventArgs e)
{
 
label1..Text = "Started";
 await DoWork();
 label2.Text = "Finished";
}

private int DoWork()
{
 return 1+2;
}

Now compiler will say a message that you can't await a method that returns void. we have to change the return type as Task or Task<T>.Now let we see the Task 

What is Task ?
    Task is an object that runs the code in separate thread from the UI thread which release the UI to do some other work.

Now we see the implemetation of await with task return type
private async void button1_Click(object sender, RoutedEventArgs e)
{
 
label1..Text = "Started";
 await Task.Run(()=> DoWork());
 label2.Text = "Finished";
}

private int DoWork()
{
 return 1+2;
}

From this article I hope you will understand the async and await operation clearly when comparing to synchronous operation, and learn to change a call sync method to await call of Task return type method.