O'Reilly logo

C# 5.0 Pocket Reference by Ben Albahari, Joseph Albahari

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Asynchronous Functions (C# 5.0)

C# 5.0 introduces the await and async keywords to support asynchronous programming, a style of programming where long-running functions do most or all of their work after returning to the caller. This is in contrast to normal synchronous programming, where long-running functions block the caller until the operation is complete. Asynchronous programming implies concurrency, since the long-running operation continues in parallel to the caller. The implementer of an asynchronous function initiates this concurrency either through multithreading (for compute-bound operations) or via a callback mechanism (for I/O-bound operations).

Note

Multithreading, concurrency, and asynchronous programming are large topics. We dedicate two chapters to them in C# 5.0 in a Nutshell, and discuss them online at http://albahari.com/threading.

For instance, consider the following synchronous method, which is long-running and compute-bound:

int ComplexCalculation()
{
  double x = 2;
  for (int i = 1; i < 100000000; i++)
    x += Math.Sqrt (x) / i;
  return (int)x;
}

This method blocks the caller for a few seconds while it runs. The result of the calculation is then returned to the caller:

int result = ComplexCalculation();
// Sometime later:
Console.WriteLine (result);   // 116

The CLR defines a class called Task<TResult> (in System.Threading.Tasks) to encapsulate the concept of an operation that completes in the future. You can generate a Task<TResult> for a compute-bound operation by calling ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required