When creating an async method in C#, I typically add the option to pass a
CancellationToken. That is the easy part. But what if a consumer of your method uses this
CancellationToken to request a cancellation? What is the proper way to cancel your code? Let's find out...
In most cases, it will be sufficient to pass the cancellation token to a lower-level API, but if we are providing the lowest-level API it is up to us to correctly handle the cancellation request.
The correct way to handle cancellations is by throwing an
OperationCanceledException when a cancellation is requested.
To help you with this, a convenient ThrowIfCancellationRequested() method exists on the CancellationToken object.
Here are some other considerations to take into account when implementing cancellation:
- Don’t cancel if you operation incures side-effects that would leave the system in an inconsistent state.
- Don’t throw an OperationCancelledException when the work has already completed.
- Start by checking if a cancellation was requested before executing your logic.
- For work that is executed very quick, it it an option to not check the token(although calling CancellationToken.ThrowIfCancellationRequested() is pretty lightweight)
- Check CancellationToken.CanBeCanceled when you can do your work more efficiently if you can assume you’ll never be canceled.