Asynchronous Programming in C# 5.0

History has seen different programming models.

  • Single Threaded Programming – Involves single execution context
  • Multi threaded Programming – Involves multiple execution contexts
  • Concurrent/Parallel Programming – Involves multiple simultaneous computations happening across multiple processors
  • Synchronous Programming – A thread executes one task at a time until it completes
  • Asynchronous Programming – A thread initiates a task, saves the state, continues with another task, and returns back to the original task once the task is complete. Hence tasks are interleaved to each other

C# 5.0 introduces async and await commands to support Asynchronous Programming. In addition .NET 4.5 contains the following APIs that support async programming

A method can be run asynchronous by prefixing with async keyword. Async methods return a Task in TPL.

“await” operator is applied while calling async method to suspend the execution of method until the awaited task completes.

Execution flow in async method

Trace an async program

Reference:

https://msdn.microsoft.com/en-us/library/mt674882.aspx