Cancellation Token
How to use CancellationToken in your .NET API requests
Give your clients the ability to cancel their requests instead of always completing it
Hey, people!
The ability to stop processing a request if your client decides that it is not necessary anymore is very important.
Some scenario that might happen is if the client sends a request through a web browser but then reloads or close this page, most of the time you don’t want to carry on those changes, as it might lead to data inconsistency.
For such scenarios where you need to stop processing a request when your client requests it, .NET provides us CancellationToken
. A very useful tool that enables us to cancel an asynchronous request.
Requirements
If you want to follow along, you need:
Here we go
To demonstrate it, let’s start by creating a new project with:
dotnet new sln CancellationToken
dotnet new webapi -minimal -n CancellationToken -o src
dotnet sln add .\src\CancellationToken.csproj
Now that we have our project, we can go to the Program.cs
and replace the GetWeatherForecast
endpoint for this:
It just logs that it received a request and then returns Hello World
.
Now to run it use:
dotnet run -p .\src\CancellationToken.csproj
And then with Postman call the endpoint. You should get the response:
Now let’s add a Task.Wait
code to mock an asynchronous request inside our method.
Now if you run Postman you should see that the request takes around 5 seconds to finish:
And see the logs stating our request flow:
Also, note the Cancel
button when you send the request. When you click on this button, Postman cancels the request. But if you do it right now, nothing happens. That is because our API doesn’t handle request cancellation yet.
To do that, we are going to add the CancellationToken
as a parameter for our endpoint.
See how we pass the CancellationToken
by just adding it as a parameter to our request. That is because .NET will implicitly add it to our request.
Now we can run again and hit the Cancel
button.
But it looks like nothing happened. But if you take a look at your logs you’ll see something different:
An exception was thrown.
This happens because when a task gets canceled, the code throws a TaskCanceledException
stating that that task was canceled.
So, to improve our code, we should add a try-catch
block between our asynchronous code and handle this exception properly.
Now if we run again, hit the Cancel
button, and check the logs, we should see the following:
Note that our LogError
was called with our message before the exception, which means that we caught it and “properly” handled it.
Conclusion
You could see how powerful and convenient it is to use CancellationToken
in your API. It gives you the ability to stop the execution of an asynchronous code when requested and it helps you prevent any undesired outcomes if your client doesn’t want a request to continue executing.
It also gives you the ability to cancel long-running and/or stuck tasks, thus freeing CPU and memory for other processes.
The code for this article can be found here.
Happy coding! 💻