Implementing a custom awaitable type

Until now we have only used Task with the await operator. However, it is not the only type that is compatible with await. Actually, the await operator can be used with every type that contains the GetAwaiter method with no parameters and the return type that does the following:

  • Implements the INotifyCompletion interface
  • Contains the IsCompleted boolean property
  • Has the GetResult method with no parameters

This method can even be an extension method, so it is possible to extend the existing types and add the await compatibility to them. In this example, we will create such a method for the Uri type. This method will download content as a string via HTTP from the address provided in the Uri instance:

private static ...

Get Mastering C# Concurrency now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.