Asynchronous : Async Await (.NET)

Rajat Sikder
2 min readJul 7, 2018

--

In my previous blog,we went over some practical use cases for asynchronous programming. In this blog, we will take a look at how asynchronous is implemented in .NET using async/await. The code snippet below describes the process (overly simplified for better understanding).

The story of two threads : thread_1 & thread_2

(Assume the code is running on a single core CPU)

From the code snippet above, the key points are :

  1. The “async” keyword enables the “await” keyword in that method
  2. The method runs synchronously until it hits an “await” or (if an exception is thrown).
  3. Without the “await” keyword, Task.Delay(5000) will run synchronously like normal methods
  4. Fun Fact! The compiler does this asynchronous using a state machine. As a result when thread_1 is called the second time, it knows from where to continue executing.
  5. The “await” takes a single argument which is called an “awaitable”. This awaitable is an asynchronous operation e.g Task.Delay(5000). There are two types of awaitables : Task<T> and Task
  6. Async methods can return Task<T>, Task or void in some exceptional cases (e.g void is used for async event handlers)

Awaitables

As mentioned above, the “await” takes a single argument called “awaitable” which is an asynchronous operation. There are two types of awaitables:

  1. Task<T>
  2. Task

Note: This means you can await the result of any method (both async and synchronous) if the method returns a Task.

For simple & short asynchronous method, avoid async/await.

Instead use non async method returning Task.FromResult. This is more efficient that using async/await.
e.g A method retrieves a value from a local cache (not an I/O operation).

I hope you found this article useful. In my next article, we will discuss consequences of context switching in asynchronous programming. We will also discuss best practices to avoid context switching unless needed. Thanks!

--

--