Await and async in .NET 4.5 with C#

A goal for any dynamic application that is meant to handle lots of traffic is the optimal usage of server resources, including the processor. The application may need to perform processes that can be carried out on different threads. In this case it’s a waste of resources to let the actions be run one after the other on the same thread and have all other available threads lying idle. Typical examples include I/O operations and complex calculations that take long to complete that block the main thread which also handles the incoming requests and thereby reduce the scalability of the application.

There are two new keywords in .NET 4.5 that help increase the scalability of your application: async and await. Be aware that these techniques introduce threading on the server, i.e. they have nothing to do with AJAX. In this case our goal is to keep the server threads busy. Also, using these keywords alone will not automatically make your code run parallel: you’ll need to extend your solution with the Task Parallel Library (TPL).

Let’s first demonstrate the usage of TPL and async/await in a Console project. So fire up Visual Studio 2012 and create a Console app.

In the console app create a class called Operation. It is initially populated with two methods:


public class Operation
{
 public string RunSlowOperation()
 {
     Console.WriteLine("Slow operation running on thread id {0}", Thread.CurrentThread.ManagedThreadId);
     Thread.Sleep(2000);
     Console.WriteLine("Slow operation about to finish on thread id {0}", Thread.CurrentThread.ManagedThreadId);
     return "This is very slow...";
 }

 public void RunTrivialOperation()
 {
     string[] words = new string[] { "i", "love", "dot", "net", "four", "dot", "five" };
     foreach (string word in words)
     {
        Console.WriteLine(word);
     }
 }
}

We’ll print the starting and ending thread IDs of the slow operation.

Call both methods from Program.cs as follows:

public static void Main(string[] args)
        {
            Operation operation = new Operation();

            string result = operation.RunSlowOperation();
            operation.RunTrivialOperation();

            Console.WriteLine("Return value of slow operation: {0}", result);
            Console.WriteLine("The main thread has run complete on thread number {0}", Thread.CurrentThread.ManagedThreadId);
            Console.ReadLine();
            
        }

…we let both operations run one after the other and also print the ID of the main thread. The result may look similar to this:
Console output

It is not surprising that we first have to wait for the slow operation to finish before the trivial task can continue. The thread ID may differ when you run this example in your VS instance. However, note that the same thread handled Main and RunSlowOperation as well.

Now we’ll let TPL enter the picture. Extend the Operation class to include the following method:

public Task<string> RunSlowOperationTask()
        {
            return Task.Factory.StartNew<string>(RunSlowOperation);
        }

…so instead of directly returning the string result we’ll only return a Task representing a method that returns a string. Edit Program.cs to call this task and get its result by using the Task.Result property as follows:

public static void Main(string[] args)
        {
            Operation operation = new Operation();

            Task<string> result = operation.RunSlowOperationTask();
            operation.RunTrivialOperation();

            Console.WriteLine("Return value of slow operation: {0}", result.Result);
            Console.WriteLine("The main thread has run complete on thread number {0}", Thread.CurrentThread.ManagedThreadId);
            Console.ReadLine();
            
        }

When you run this then you will see that the slow operation did not block the main thread and the trivial operation could continue:
Console output

You’ll notice that the programme was carried out on two threads: one for the main thread and one for RunSlowOperation().

We’ll now include async and await to increase the efficient usage of our resources.

We can include the keyword async to method to make it asynchronous. An async method must have ‘await’ somewhere in its body otherwise the VS will complain. The await keyword indicates that the task it denotes can be suspended until some other task is complete. While the async method is suspended the caller is free to continue with what it is doing. This means that the thread that starts an async method may jump out of it at the await keyword and a different thread will jump in again and continue where the previous thread left off.

Async methods should always return a Task or a Task of T. The name of the async method should end with ‘Async’ to indicate to the caller that it is in fact an asynchronous method. The await keyword can occur more than once within the method body.

Extend Operation.cs to include the following method:

public async Task<string> RunSlowOperationTaskAsync()
        {
            Console.WriteLine("Slow operation running on thread id {0}", Thread.CurrentThread.ManagedThreadId);
            await Task.Delay(2000);
            Console.WriteLine("Slow operation about to finish on thread id {0}", Thread.CurrentThread.ManagedThreadId);
            return "This is very slow...";
        }

Note that Thread.Sleep was replaced by Task.Delay(2000). Thread.Sleep blocks the thread whereas Task.Delay represents a work that will block the thread for two seconds. At that point the thread that started the method may jump out of the method and let a different thread complete it to completion when the Task has finished.

Modify Program.cs as follows:

public static void Main(string[] args)
        {
            Operation operation = new Operation();

            Task<string> result = operation.RunSlowOperationTaskAsync();
            operation.RunTrivialOperation();

            Console.WriteLine("Return value of slow operation: {0}", result.Result);
            Console.WriteLine("The main thread has run complete on thread number {0}", Thread.CurrentThread.ManagedThreadId);
            Console.ReadLine();
            
        }

The output may look as follows:

Console output

We have some differences compared to the previous case:

  • The slow operation starts on the same thread as Main whereas it started on its own thread before
  • The slow operation completed on a different thread from the one that started it
  • The main thread jumped out of the long running method and continued with the trivial method of printing the string array elements

When the main thread encountered the await keyword it ‘knew’ that it could leave the long running method and let a different thread take over and finish it. The beauty of this is that the new thread that took over from the main thread will have the necessary context data available: HTTP context, identities, culture settings. The thread synchronisation job is taken care of by .NET behind the scenes.

Note that this behaviour is not guaranteed to occur: in some cases, such as Silverlight, the UI thread must stay constant. However, the benefit is that the UI will not freeze when it encounters a long running method: it can still stay active and react to user inputs.

To summarise:

  • Async and await help make the usage of processing threads more efficient
  • They will not make your code run parallel without the TPL
  • The thread that started an async method may not be the same as the one that finished the method
  • The available threads will not just lie idle and block incoming requests while waiting for a task to finish

In the next blog we’ll look at async/await in MVC4.

View the list of MVC and Web API related posts here.

Advertisement
Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: