Why you should use Cancellation Tokens in your Code

Bending the Clean Architecture Principles

Anthony Trad
3 min readJul 5, 2022

Introduction

When you’re writing code, regardless of the language, you certainly encountered some sort of Concurrent, Parallel, Multithreading… While these terms are slightly different, I will leave that to another article and explain a common practice you should do while using them.

What

Let’s start with what is Cancellation Tokens, let’s say you’re using an application on your phone, you requested some lengthy operation like exporting all your data, do some analysis… You waited for 1, 2 10, 20 mins and the loading is still displayed, without any progress bar. So you start to wonder, is my application crashing? Freezing? Is the process actually running?

You don’t have any ETA so when your patience wears out, you decide to cancel whatever you’re looking for and do something else right? It’s very common especially with long running processes…

Did you ever think how would your app behave when you do such a thing? Does it automatically knows that you’re not interested anymore in this information, or the process continues anyway?

Why

Let me break it to you, your app will most likely continue on whatever you don’t need, wasting your precious cloud and costly resources, slowing down all the next requests and you should be able to prevent that. Here’s why you need Cancellation Tokens. This token will get triggered whenever you’re not waiting or listening for this particular response, and exit accordingly.

Tokens are passed down from top to bottom, it spreads out just like the async await operator in most languages… And it should really, having one indicates that you can exit and end your database connection if you’re not listening anymore.

What’s more important is that it also prevents cascading calls, if you’re like me and you like to spam buttons in your app. If you get on the Get Customers 10 times, you are only listening to the last response, and adding that to your view. All the other 9 should just end and exit before getting to the database, why would we go with the entire flow if we don’t care about the result.

How

So we know why and when it is used, but how can you implement and handle this process for existing early?

CancellationTokenSource comes to the rescue. Basically adding that to your handler and calling the .Cancel() method will let you exit early from what you’re doing. Yes, it is THAT easy.

In fact, it is also easier in most of the frameworks. In an API context, you don’t even have to do that as it is done behind the scenes. This token is automatically filled within each HTTP context, so you don’t have to Cancel it manually.

Just add the CancellationToken parameter to your endpoint, pass it down to your task that can be canceled. It can be a ToListAsync() from EF Core or any other Async operation really. Most of them supports them automatically.

Conclusion

When we decide if we should implement something, we measure if the benefits outcomes the efforts needed to implement this. In our case, I found myself always using Cancellation Tokens as the performance gains are very significant compared to the effort of adding a parameter and passing it down..

--

--

Anthony Trad
Anthony Trad

Written by Anthony Trad

Senior Software Engineer focused on .NET and the Cloud. Reconsidering major principles and patterns, ideas are my own.

Responses (1)