Custom awaitable and awaiter types in C# 5.0 asynchronous

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()
    {
       
    }
}
Advertisement

2 thoughts on “Custom awaitable and awaiter types in C# 5.0 asynchronous

  1. Hi there everyone, it’s my first visit at this site, and piece of writing is genuinely fruitful in support of me, keep up posting such articles or reviews.

Leave your comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s