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 ...

Get C# 5.0 Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.