Async and Await

Microsoft is recommending to use a pattern called TAP (Task-based Asynchronous Pattern) for new projects who needs to use, guess what, asynchronous tasks (really? :o).

Look at this synchronous code:


using System;
using System.Threading;

namespace MyCode
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Doing something before calling the task.");
            new ServiceLayer().DoHeavyJob(1000);
            Console.WriteLine("Doing something after calling the task.");
        }
    }

    class ServiceLayer
    {
        public void DoHeavyJob(int timeToComplete)
        {
            Console.WriteLine("The task is running. Please wait!");
            Thread.Sleep(timeToComplete);
            Console.WriteLine("The task has been completed!");
        }
    }
}

With it, you’ll get this output:

Doing something before calling the task.
The task is running. Please wait!
The task has been completed!
Doing something after calling the task.

If you’re pretending to turn the heavy task into something asynchronous, then you may accustomed to doing something like this:

static void Main(string[] args)
{
    Console.WriteLine("Doing something before calling the task.");
    var thread = new Thread((o) => {
        new ServiceLayer().DoHeavyJob(1000);
    });
    thread.Start();
    Console.WriteLine("Doing something after calling the task.");
    thread.Join();
}

And you get, as you know, this output:

Doing something before calling the task.
Doing something after calling the task.
The task is running. Please wait!
The task has been completed!

Well, this is past.

C# now has two keywords (since .net 4): async and await, where async makes your method, guess what, asynchronous! Yes! Just it. And await is a keyword that work with Tasks, something like promises in JavaScript.

So, the goal here is to make your code more legible and easy to maintain.

Here is the same as the second code using this new and beautiful keywords:

using System;
using System.Threading.Tasks;

namespace MyCode
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Doing something before calling the task.");
            var task = new ServiceLayer().DoHeavyJob(1000);
            Console.WriteLine("Doing something after calling the task.");
            task.Wait();
        }
    }

    class ServiceLayer
    {
        public async Task DoHeavyJob(int timeToComplete)
        {
            Console.WriteLine("The task is running. Please wait!");
            await Task.Delay(timeToComplete);
            Console.WriteLine("The task has been completed!");
        }
    }
}

Looks more simple, isn’t it? Yes, I know.

May you note a stranger thing in output:

Doing something before calling the task.
The task is running. Please wait!
Doing something after calling the task.
The task has been completed!

A mix in the order.

This is because the heavy job starts after “The task is running. Please wait!” and once your heavy code is running, it will not freeze your app, webapp, windows forms or whatever are you doing.

You may asking to yourself what are await actually doing!

Await do not turn your asynchronous method into a synchronous method. Your method continues to run asynchronously to who calls it, but synchronized with Task.Delay. This is useful when you are using some asynchronous method of .Net Framework, for example, to send a lot of emails or read a lot of files, etc.

Here an example using Thread.Sleep instead of Task.Delay:

public async Task DoHeavyJob(int timeToComplete)
{
    await Task.Run(() =>
    {
        Console.WriteLine("The task is running. Please wait!");
        Thread.Sleep(timeToComplete);
        Console.WriteLine("The task has been completed!");
    });
}

And the result will be the same.

This is just a basic explanation and I hope it has been useful to you.

Have fun! =)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s