How to await a CancellationToken

Cancellation tokens are a way for asynchronous operations to allow the caller to cancel them. The mechanism is pretty damn robust – the same token can be propagated along multiple nested operations such that a cancellation of the top-level object will cancel whichever operation happens to be running right now.

Sometimes, when implementing your own Task returning method, you may find yourself wanting to simply wait for a cancellation token to “pop”. One example for this is if as part of your asynchronous operation you are waiting for user input, one option of which is to cancel the operation.

Surprisingly (for me), a cancellation token does not seem to have an awaitable entry point. A small extension function though and you can easily do it. The bulk of the code (the AsyncManualResetEvent) is actually not part of this blog, but exists in the very excellent blog by Stephen Toub.

Once you have access to AsyncManualResetEvent, simply add this extension method to your project and you are good to go:

public static Task AsAwaitable(this CancellationToken token)
var ev = new AsyncManualResetEvent();
token.Register(() => ev.Set());
return ev.WaitAsync();

This entry was posted in Dev, Windows8. Bookmark the permalink.

Leave a Reply

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

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

Twitter picture

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

Facebook photo

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

Connecting to %s