Thursday, November 12, 2015

Async Await in C#

In today's blog post, I will be talking about how to do asynchronous programming in C# using async await keywords.

ASYNC AWAIT

Earlier (before C# 5), writing asynchronous code used to be difficult and bug-prone. With C# 5 came async await which made writing asynchronous code lot easier.


Async Await C#



Let's take a look at a simple example of how to do this.
In order to demonstrate this, I created a small web form application which looks like this:


Web Form .NET Async Await C#


The code behind looks like this:


public Form1()
{
    InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
    var result = SlowMehtod("Abhi");
    label1.Text = result;
}

private string SlowMehtod(string str)
{
    Thread.Sleep(2000);
    return "Welcome " + str;
}



So when I click the button, it updates the label1 text to "Welcome Abhi". However, as you can see I added a Thread Sleep statement to add a delay of 2 seconds. The reason why I did this is to make the method slow (who does that!). In your code, you might have some method which accesses resource over the web or some database or due to some other reason, its slow. I just simulated the slow behavior. So when I click the button, my form freezes for 2 seconds and then it shows "Welcome Abhi".

If we are blocking the UI thread, we are basically freezing the application and making the user experience not pleasant. The user might think that application is frozen and might just kill the process. So we should avoid blocking the UI thread.

By wring asynchronous code, we can put the slow method to execute in parallel. Let's take a look at how we can do that here:

private void button1_Click(object sender, EventArgs e)
{
    CallSlowMethodAsync("Jain");
    label1.Text = "Waiting...";
}

private async void CallSlowMethodAsync(string str)
{
    var result = await SlowMehtodAsync("Jain");
    label1.Text = result;
}

private Task<string> SlowMehtodAsync(string str)
{
    return Task.Factory.StartNew(() => SlowMehtod(str));
}

private string SlowMehtod(string str)
{
    Thread.Sleep(2000);
    return "Welcome " + str;
}

For writing async code, we simply created a new method with async keyword. Inside async method, there is await which marks the method that will be executed in parallel. The await calls the SlowMethodAsync which return a Task<string>.  By convention the name of the async method ends with an "Async" suffix. The return type of async method can be:

  1. Task<TResult> - if method is returning something of type TResult.
  2. Task - if method has no return statement or empty return statement.
  3. Void - if it's async event event handler.

So now when I run this application, and I click the button, the label text changes to "Waiting..." right away. Then after 2 seconds, it updates to "Welcome Jain". During the time the SlowMethod() is running, the UI doesn't freeze anymore as it's running asynchronously :)

Web Form .NET Async Await C#


Conclusion

C# 5 makes it very easy to write asynchronous code and we should use this feature when we have any slow running code threatening our user experience ;)

For future updates to my weekly blog, please subscribe to my blog via the "Subscribe To Weekly Post" feature at the right and follow me on Twitter. Until then Happy Coding :)


No comments:

Post a Comment