Using a CancellationToken in .NET Core Web API
This blog is a guide on how to use a CancellationToken in a .NET Core Web API, using the default template example of the weather forecast.
Happy path scenario
To demonstrate this we will use the weather forecast endpoint, it returns details such as temperatures, the data is randomly generated. In a real world scenario this data could be stored in a SQL database or returned from another HTTP request. So when a person requests the local weather forecast there is a dependency, in this example imagine it is a datastore.
To test this out I added console messages so we can see what is going on. I also added a Task Delay of 5 seconds in order to mimic a database call. Using Postman I called the GET weather forecast endpoint, the console messages below were as expected, as were the number of results.
What would happen if…a user made the request then immediately closed the browser, navigated to a different website or made one request quickly followed by another? Let’s find out.
For the second attempt I called the weather forecast endpoint however cancelled the request. As you can see in the console output below the call completed although the request was cancelled and the results were still returned.
To solve this matter in order to protect our database and resources, we can use a CancellationToken. They are used to control the execution flow of the tasks, business logic or algorithm conditions.
Now the application will continue to process new requests however if a request is cancelled, it will throw a TaskCanceledException.
There are many advantages which include:
- Cancellation of asynchronous operations or long-running synchronous operations
- Protecting the CPU of resources and thread pools
- Avoiding duplication of records when creating, updating or deleting
- Saving time by not running the Task
In summary, providing a cancellation token is good practice as it saves resources and time. There have been some changes around Cancellation in .NET 6, which is covered in a Microsoft blog ‘Performance Improvements in .NET 6’ .
This blog covered the basics of using a CancellationToken, for further reading: