Work Hours
Monday to Friday: 8am – 6pm
Weekend: 10am – 2pm
Embracing good programming practices not only ensures efficient resource utilization but also facilitates seamless application scaling. One such practice is using CancellationToken in C#. In this article, we’ll explore why CancellationToken is beneficial and how it can prevent resource wastage, especially in scenarios where long-running tasks may become problematic.
Why Use CancellationToken
Consider a scenario where a database query is executing a time-consuming operation, generating data for REST API response. Unfortunately, query is cancelled by application during this process. Nobody will be waiting for the result. To prevent wasting resources on incomplete tasks, CancellationToken comes into play. It allows us to gracefully cancel operations that might be too time-consuming, saving resources and preventing generating unnecessary results.
Why Use async in Method Names
The async suffix in method names signifies that the method is asynchronous. While calling an asynchronous method is not always synchronous (we don’t always use await
), the async naming convention provides a quick visual mark that the method involves asynchronous operations. It’s a good practice for code readability and understanding the nature of the method at a glance.
Practice
When using CancellationToken, it’s common to encounter one of two exceptions upon cancellation: TaskCancelledException
or OperationCancelledException
. Handling these exceptions in our code is crucial. Creating a generic middleware to manage CancellationToken exceptions simplifies this process.
CancellationToken itself acts as a pointer to a class that manages tokens.
It works more or less as follows: we create ourselves a source that has a token in it, which has a field to check if it has been activated and has the ability to throw an exception:
Typically, we pass the token up to the final method responsible for handling it, such as a database or any I/O operation that may be time-consuming.
Let’s explore examples of using CancellationToken:
Example with if
Example with exception
Example with callback function
Once token.IsCancellationRequested
evaluates to true, we gracefully exit our extensive loop. It’s crucial to emphasize that every time we instantiate a CancellationTokenSource
using cancelTokenSource = new CancellationTokenSource();
, it is imperative to remember to call cancelTokenSource.Dispose();
to properly release allocated resources.