In C# 5.0 you can use the await
keyword to await an awaitable
object. But what is the minimum requirement for an object to be considered awaitable
by C#? Interestingly there are no interfaces to be implemented in order to be considered awaitable
!
Having a parameter-less method named GetAwaiter()
which returns an awaiter
object is the only convention for a type to be recognized awaitable
by C#:
// This class is awaitable because it has the GetAwaiter method, provided MyAwaiter is an awaiter. public class MyWaitable { public MyAwaiter GetAwaiter() { return new MyAwaiter(); } }
Now the question is how to make a type awaiter
? The minimum requirements for a type to be awiater
are implementing the INotifyCompletion
interface, and having the IsCompleted
property and the GetResult
method with the following signatures:
public class MyAwaiter : INotifyCompletion { public void OnCompleted(Action continuation) { } public bool IsCompleted { get { return false; } } public void GetResult() { } }