Using Cancellation Tokens in ASP.NET Core MVC — Part 2

Prashant Kumar
3 min readSep 17, 2022

In the previous article — Using Cancellation Tokens in ASP.NET Core MVC — Part 1, we have seen what is CancellationTokenSource, CancellationToken and how to use them in different scenarios to cancel a long-running operation.

In this second part, we will discuss a very specific but very important use case of the CancellationToken. We will see how we can use CancellationToken in the ASP.NET Core action method to stop execution whenever the call has been canceled.

Even after the cancellation has been requested either from the browser or the library code, Action Methods continue to execute the remaining instructions in absence of a cancellation mechanism.

To understand the drastic negative impact of this, let’s assume a scenario where a library code has called Some Data Api with a 10 seconds timeout policy. Data API connects with the database and sends a Query execution instruction that will take more than 10 seconds in its execution. Since the library code has a Timeout Policy to terminate the tasks, it will wait for 10 seconds and will terminate the task and throw an OperationCanceledException or a TaskCanceledException. But Data API will continue to wait for the database response and complete its execution. This might cause the throttling of the servers and a bad user experience.

The following code contains the ISomeService interface which has the definition of two long-running synchronous and asynchronous operations. HighCostService service implements the interface but doesn’t respond to the cancellation request. OptimizedService also implements the same interface but respond to the cancellation request.

In the following code, the ASP.NET Core controller received an object for the ISomeService interface based on the user preference. Both of the action methods log the incoming HTTP Request and attached a delegate to the received CancellationToken object.

High-Cost Service — HTTP Request

In first example, when we execute the action method with HighCost ServiceType and cancel the request from browser before the completion of the request, action method continue to execute the remaining instructions.

High Cost — HTTP Request

Optimized Service — HTTP Request

In the second example, when we execute the action method with Optimized ServiceType, it honors the cancellation token and terminate the request and execute the attached callback/delegate.

Note: These callbacks should be fast as control will not return the source until all the callbacks have been executed.

Log Cancelled request using Exception Filter

Although changed Status code and written response will be received by the client, it can be used to generate a metric of cancelled requests.

HTTP Status Code: 499 (CLIENT CLOSED REQUEST)

It’s a non-standard status code introduced by nginx for the case when a client closes the connection while nginx is processing the request.

--

--