Saturday, June 10, 2017

Async and Await - Asynchronous Programming


Microsoft introduced Async and Await keyword with .Net framework 4.5. Async and Await keyword can be used to improve your application’s overall responsiveness by using asynchronous programming. Asynchronous programming is essential when your application is doing some activity which makes UI unresponsive. You can move that activity to execute asynchronously so it doesn’t block UI and your application will be responsive.

You should consider using Async and Await when you want to keep your application responsive. Async method provides easier way to do long running work in background without blocking thread. Ideally method is decorated with Async keyword should contain one await statement. If you don’t write await statement in Async method, it won’t give compile error but execute as synchronous method.

Below are few things to remember about Async and Await method.

  • The method should contain async modifier.
  • Async method return type should be
    • Task
    • Task<T>
    • Void
  • The method usually includes at least one await expression.

Let’s have a look on below example.

Code –

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }
    public async void DoSum(int number)
    {
        Console.WriteLine("Task started");
        var result = Calculate(number);
        Console.WriteLine("Task completed");
        if (!result.IsCompleted)
            await result;
        Answer.Text = result.Result.ToString();
        Console.WriteLine(string.Format("Answer is {0}", result.Result.ToString()));
    }
    public async Task<int> Calculate(int number)
    {
        var sum = 0;
        Task myTask = new Task(() =>
        {
            for (int i = 1; i <= number; i++)
            {
                System.Threading.Thread.Sleep(1000);
                sum += i;
            }
        });
        myTask.Start();
        await myTask;
        return sum;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        if (!string.IsNullOrEmpty(Input.Text))
        {
            Console.WriteLine("Sum process started");
            var number = Convert.ToInt32(Input.Text);
            DoSum(number);
            Console.WriteLine("Sum process completed");
        }
    }
}

Output –

Sum process started
Task started
Task completed
Sum process completed
Answer is 55



As you can see in output, the UI doesn’t block and cursor immediately return to UI. The sum is calculated and updated asynchronously after all execution completed.

Now let’s make little change to this programme and use Task.Wait() method to complete task instead of await. I added myTask.wait() instead of await myTask.

public async Task<int> Calculate(int number)
{
    var sum = 0;
    Task myTask = new Task(() =>
    {
        for (int i = 1; i <= number; i++)
        {
            System.Threading.Thread.Sleep(1000);
            sum += i;
        }
    });
    myTask.Start();
    myTask.Wait();
    return sum;
}

Output –

Sum process started
Task started
Task completed
Answer is 55
Sum process completed

As you can see in output, till the sum is calculated UI is blocked and after that sum process is completed. That means myTask.wait() blocks the thread until task completed.

Difference between await and task.wait() - 

Task.wait blocks the thread and await doesn’t block thread and UI.

I hope this article helps you to know more about async and await. Please leave your feedback in comments below.

You can download full code from Gist.

See also –


No comments:

Post a Comment