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: