Cancellation Token in .NET is a neat & easy way to manage the asynchronous task execution. The goal of Cancellation Token is to gracefully stop an asynchronous task instead of abruptly killing it. From an architecture perspective, gracefully handling logic is a ultimate must. So, developers need to know that there are many different ways other than Try-Catch Exception Handling technique exist.
In this blog, I will explain with the help of a codebase on how to use Cancellation Token in .NET.
In this program, there are 3 different things to mainly understand.
- CancellationTokenSource – This is a class that provides the ability to cancel an asynchronous operation
- CancellationToken – Holds the cancellation request in the form of a token.
- Task – The actual asynchronous operation which will carry a reference of the token along with it.
In Line no 13, we are creating an instance of a CancellationTokenSource to play with the concept of cancelling a task execution.
In Line no 14, you can see clearly that it is from the tokenSource that you get a CancellationToken object.
At Line no 25, the asynchronous task is created & started. Notice that the Task.Factory.StartNew takes an action (anonymous/actual method) along with a token object (in line no 41). Because the task knows the token, it can keep checking if the token signals for a cancellation/not (which is implemented in line no 30).
In the code, I am requesting for cancellation when I press the “c” key in the keyboard. At this time, the tokenSource conveys the cancel message to cancellationToken object which is in turn sensed by the task.
When the cancellation is sensed in the task, we can use token.ThrowIfCancellationRequested() method to throw an operation cancelled exception. This exception will be caught in the try-catch block that waits for the task to finish execution (at line no. 54).
The output is as shown below:
Note: While debugging this codebase, you might see an unhandled exception as shown below. It is because we are debugging the application. You just need to hit the “Continue” button and the application will run properly. In production, the application executes in Release mode. Therefore, you will not see this unhandled exception (because it is actually handled) in Release mode but will alert you in Debug mode.