Awaitable

This lesson explains the awaitable concept in C#

Awaitable

In our previous example, we have used the await operator with objects of type Task. What types are allowed to be used with the await operator? The requirements are as follows:

  • The type should have a method GetAwaiter() that returns an instance of a class satisfying specific properties. Say if the return type is class X then it must meet the following bullet points.

  • X must implement the interface INotifyCompletion and optionally the ICriticalNotifyCompletion interface.

  • X must have an accessible, readable instance property IsCompleted of type bool.

  • X must have an accessible instance method GetResult() with no parameters and no type parameters.

A type which satisfies the above requirements can be used in an await expression. The Task class meets all the above requirements.

Working of await

What happens when an await expression is evaluated? The official documentation offers the most succint and comprehensive description which we preesent verbatime as below:

"The await operator suspends evaluation of the enclosing async method until the asynchronous operation represented by its operand completes. When the asynchronous operation completes, the await operator returns the result of the operation, if any. When the await operator is applied to the operand that represents already completed operation, it returns the result of the operation immediately without suspension of the enclosing method. The await operator doesn't block the thread that evaluates the async method. When the await operator suspends the enclosing method, the control returns to the caller of the method."

Think about await as points defined in a program from which threads can leave and return to at some later time in the future.

Awaitbale Example

Now that we understand the basic working of await/async, we'll write a class that we can await. In our example from the previous section, we used the method Task.Delay() to asynchronously wait for a specific duration. Now we'll build a class that can be passed-in the number of milliseconds to sleep. Let's see the skeleton of our class first:

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.