Save Resources Using CancellationToken In ASP.NET Core API

Christ khodabakhshi
5 min readDec 28, 2023

In this article, we are going to explain what is CancellationToken and the way to implement it in your Asp.Net Core APIs.

What is CancellationToken

If I want to put it in one sentence, CancellationToken is a token object providing a mechanism to stop long-running and async operations before the process is finalized (due to the client’s request).

Let’s imagine a scenario where you have a front-end application that is making an HTTP Get request to an endpoint which is performing a long-running operation on a large amount of data and responses to it. The end-user can close the browser or just move to another page and doesn’t need that result anymore, by having the ability to cancel the request in the middle of the operation when the user doesn’t need it anymore we will save some resources especially if we have a huge amount of users. Therefore; .NET made the CancellationToken and when the request-making client sets the token we will get the mentioned benefit.

When & Why You Should Consider Implementing CancellationToken

--

--

Christ khodabakhshi

Software developer, dad, coffee fan, and keen on talking about business ideas and investments.