In C# asynchronous programming, a CancellationToken allows you to stop a Task. This is especially useful if you have many Tasks running and want to gracefully shut down the program, or if you want to add a timeout to a Task.
Creation
CancellationTokens are created from a CancellationTokenSource.
Usage
The token represented by the CancellationTokenSource is accessed via the CancellationTokenSource’s Token property
You can check if the CancellationTokenSource has been canceled from either the CancellationTokenSource itself or the CancellationToken. This can be useful if you’re writing some code that does a few different things asynchronously, but you want to check to make sure Cancel wasn’t initiated before moving on to the next thing.
Canceling
To Cancel a token, use the Cancel method on the CancellationTokenSource:
TaskCanceledException and OperationCanceledException
Important – When a task is canceled, it *will* throw an exception. In an ideal, happy-path kind of world, exceptions shouldn’t be thrown, but if a Task is canceled it should be a rather exceptional case, so this exception is how you can key on and handle those cases.
TaskCanceledExceptions inherit from OperationCanceledException, and sometimes it is better to catch the OperationCanceledException instead of the TaskCanceledException. There are some methods that can take a CancellationToken parameter, but, when the token is canceled, throw an OperationCanceledException because the underlying implementation isn’t actually doing anything with Tasks. A notable example is the BlockingCollection.TryTake:
Waiting for a keypress asynchronously in a C# console app – Darchuk.NET
[…] make use of the cancellation tokens. I’ve talked about them before, but they allow you to cancel in-flight asynchronous operations. Essentially, we will want to […]