Using the Await Keyword with Asynchronous Code in C#

So I hear that when they were planning Windows 8, Microsoft did all this research and determined that, if you give a programmer the choice between doing something synchronously and doing it asynchronously, then 99.9 times out of 100 they’ll do it synchronously.  Hearing this, Microsoft decided to take away the option, and just force everybody to do things asynchronously, all the time. Because apparently we’re all expected to do all our computing on phones now, and phones are still kind of bad at computing at the moment.

In an attempt to assuage the 99.9% of programmers who resent having their code rendered unreadable when their nice pretty methods are split up into 17 callbacks apiece, Microsoft added the “await” keyword to .NET.  Basically, it allows you to make those 17 asynchronous callbacks look like a single method again. Sort of, anyway.  There are caveats.

The code shown below uses the await keyword to call an asynchronous method that calculates the sum of the first n integers. For large values of n, this calculation may take several seconds to complete. When the calculation method completes, the runtime will then start executing the code that appears after the await statement in the calling method.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplicationAwait
    class Program
        static void Main(string[] args)

        static async void callLongTaskAsynchronously()
            int numberOfIntegersToAdd = 1000000000;
                "About to calculate sum of first " 
                + numberOfIntegersToAdd 
                + " integers asynchronously..."
            Console.WriteLine("About to await...");
            long result = await Task.Run(() => calculateSumOfFirstNIntegers(numberOfIntegersToAdd));
            Console.WriteLine("Done with await...");
            Console.WriteLine("Result of asynchronous procedure: " + result);
            Console.WriteLine("Press any key to quit.");

        static long calculateSumOfFirstNIntegers(long numberOfIntegersToAdd)
            long returnValue = 0;

            for (long i = 1; i <= numberOfIntegersToAdd; i++)
                returnValue += i;

            return returnValue;


  • Your code may look a little neater when you use the await keyword, but remember that it’s still not really synchronous. The method in which the await keyword appears will return immediately to the calling scope, which then continues on its merry way. So the Console.ReadKey() in the Main() method of the program above will be called before the “calculateSum” method completes. Which means if you hit a key before the calculation finishes, your program will finish without showing any results.
  • That usage of Task.Run is kind of ugly, but it’s still cleaner than all the other examples I could find. Or at least it was the least ugly of all the ones that I could get to run at all. In previous betas of C# 4.5 (or whatever version it is), I think they used a slightly different set of methods and classes, which don’t seem to work now. Anyway, if you can figure out a better way, use it.
This entry was posted in Uncategorized and tagged , , . Bookmark the permalink.

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s