The best way to use cancellation tokens in ASP.NET Core 7

Deal Score0
Deal Score0

Though ASP.NET Core 7 is the most recent model of Microsoft’s open supply net utility improvement framework, it takes benefit of numerous vital options from earlier variations of .NET. Considered one of these vital options is cancellation tokens, which give a approach of gracefully dealing with multi-threaded functions.

When working with ASP.NET Core functions, it’s good follow to make lengthy working operations (similar to a database question or background course of) cancelable, both after a sure size of time or upon consumer request, in order that the applying can launch assets and stay responsive. Right here’s the place cancellation tokens come into play.

This text discusses cancellation tokens, why they’re helpful, and find out how to use them in minimal API handlers in ASP.NET Core. To work with the code examples offered on this article, you must have Visible Studio 2022 Preview put in in your system. When you don’t have already got a replica, you possibly can download Visual Studio 2022 here.

Create an ASP.NET Core 7 minimal Net API mission in Visible Studio 2022

First off, let’s create an ASP.NET Core minimal API mission in Visible Studio. Following these steps will create a brand new ASP.NET Core 7 Net API mission in Visible Studio 2022 Preview:

  1. Launch the Visible Studio 2022 Preview IDE.
  2. Click on on “Create new mission.”
  3. Within the “Create new mission” window, choose “ASP.NET Core Net API” from the listing of templates displayed.
  4. Click on Subsequent.
  5. Within the “Configure your new mission” window, specify the identify and placement for the brand new mission.
  6. Optionally examine the “Place answer and mission in the identical listing” examine field, relying in your preferences.
  7. Click on Subsequent.
  8. Within the “Further Data” window proven subsequent, uncheck the examine field that claims “Use controllers…” since we’ll be utilizing minimal APIs on this instance. Go away the “Authentication Sort” as “None” (default).
  9. Make sure that the examine packing containers “Allow Docker,” “Configure for HTTPS,” and “Allow Open API Assist” are unchecked as we gained’t be utilizing any of these options right here.
  10. Click on Create.

We’ll use this ASP.NET Core 7 Net API mission to create minimal API endpoints and work with cancellation tokens.

What are cancellation tokens? When ought to we use them?

A CancellationToken is a light-weight object created by a CancellationTokenSource occasion. When a CancellationTokenSource is canceled, all shoppers of CancellationTokens are notified accordingly. Moreover, the IsCancellationRequested property of the cancellation token occasion is about to true, indicating that the CancellationTokenSource has been canceled and cancellation of the duty has been requested.

You should utilize a CancellationToken to cease a protracted working operation when the consumer cancels a request within the net browser. In different phrases, utilizing a CancellationToken will help you cease lengthy working requests from utilizing assets when the consumer has stopped or refreshed the online web page.

You should utilize CancellationTokens to cease async duties as properly. In an async job, cancellation signifies that the duty ought to stop performing its present exercise. An async job receives a cancellation token and examines it to see if a cancellation is requested. If that’s the case, the present operation ought to stop instantly.

Lengthy working requests in ASP.NET Core

When engaged on net functions, you would possibly usually make use of lengthy working duties, i.e., database calls, file dealing with, and many others. When an object creates a number of lengthy working operations, it ought to cross cancellation tokens to all of these operations. Cancellation tokens also needs to be handed to different inside operations.

Finally, the article that created the lengthy working operations might — after a time deadline is reached, or when a consumer stops a request — propagate a cancellation notification to those cancellation tokens. It must be famous that every one lengthy working operations should respect the cancellation request and cancel the lengthy working operations in order that assets might be launched.

Listening for cancellation requests in ASP.NET Core

You possibly can pay attention for cancellation requests by polling the worth of the CancellationToken.IsCancellationRequested property as proven within the code snippet given under.

     //Write your code right here to carry out some operation

One other approach to pay attention for cancellation requests is to name the ThrowIfCancellationRequested technique, as proven within the code snippet given under.

     //Write your code right here to carry out some operation

And you’ll pay attention for cancellation requests by registering a callback as proven within the following code snippet.

WebClient webClient = new WebClient();   
cancellationToken.Register(() =>

Create a minimal API handler in ASP.NET Core

Let’s now simulate a protracted working request and see how cancellation works. First we’ll strive a protracted working request with out cancellation. Write the next piece of code within the Program.cs file.

app.MapGet("/hi there", async () =>
    app.Logger.LogInformation("Request began at: "+DateTime.Now.ToLongTimeString());
    await Activity.Delay(TimeSpan.FromSeconds(5));
    app.Logger.LogInformation("Request accomplished at: " + DateTime.Now.ToLongTimeString());
    return "Success";

Once you execute this utility and hit the /hi there endpoint, you will note that the handler executes in its entirety even for those who attempt to cease the request by refreshing the online browser as proven in Determine 1.

cancellation tokens 01 IDG

Determine 1: With out cancellation, the handler executes in its entirety even when the request is aborted by the consumer.

Use a CancellationToken in a minimal API handler

The next code itemizing reveals how one can inject a CancellationToken into our endpoint handler and cross this token to the Activity.Delay technique.

app.MapGet("/hi there", async (CancellationToken token) =>
    app.Logger.LogInformation("Request began at: " + DateTime.Now.ToLongTimeString());
    await Activity.Delay(TimeSpan.FromSeconds(5), token);
    app.Logger.LogInformation("Request accomplished at: " + DateTime.Now.ToLongTimeString());
    return "Success";

Now if you execute the applying and hit the /hi there endpoint, refreshing the online browser earlier than the request completes will cease the request. You’ll see from the logs that the request by no means completes. As a substitute, a TaskCancelledException will likely be thrown as a result of the CancellationToken.IsCancellationRequested property will likely be set to true.

The exception messages will include the hint info on the aborted request as proven in Determine 2.

cancellation tokens 02 IDG

Determine 2: When cancellation has been used within the handler code, a request that’s aborted halfway is not going to full.

Checking cancellation state in ASP.NET Core

You would possibly usually wish to know if cancellation has been requested on a cancellation token. You possibly can examine the cancellation state by analyzing the IsCancellationRequested property. The IsCancellationRequested property will likely be true (i.e., can have a boolean worth of true) if cancellation has been requested on the token, false in any other case.

As talked about above, the CancellationToken.ThrowIfCancellationRequested technique will throw an OperationCanceledException if the cancellation token occasion has requested cancellation.

The next code snippet illustrates how the IsCancellationRequested property can be utilized to examine if the token has requested cancellation. If the request has been cancelled, an occasion of OperationCanceledException is thrown.

if (token.IsCancellationRequested)
    app.Logger.LogInformation("Request has been cancelled..");
    throw new OperationCanceledException();

Utilizing cancellation tokens is an effective follow, however it isn’t at all times advisable in your controller motion strategies. If the request modifies the state, you’ll not need such a request to be cancelled. Cancellation tokens are helpful primarily for lengthy working calls that devour vital assets, when stopping the request is not going to have any unintended effects.

Lastly, for the needs of this text, we used Activity.Delay to simulate a protracted working operation. As a replacement, you possibly can substitute any lengthy working calls particular to your utility’s necessities similar to database calls, community calls, file dealing with operations, downloading information from the web, and so forth.

Copyright © 2022 IDG Communications, Inc.

We will be happy to hear your thoughts

Leave a reply
Enable registration in settings - general