Wednesday, October 5, 2022
HomeITuse cancellation tokens in ASP.NET Core 7

use cancellation tokens in ASP.NET Core 7


Though ASP.NET Core 7 is the most recent model of Microsoft’s open supply internet software improvement framework, it takes benefit of numerous vital options from earlier variations of .NET. One in all these vital options is cancellation tokens, which give a approach of gracefully dealing with multi-threaded purposes.

When working with ASP.NET Core purposes, it’s good observe 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 sources and stay responsive. Right here’s the place cancellation tokens come into play.

This text discusses cancellation tokens, why they’re helpful, and easy methods to use them in minimal API handlers in ASP.NET Core. To work with the code examples offered on this article, you need to have Visible Studio 2022 Preview put in in your system. For those who don’t have already got a replica, you may obtain Visible Studio 2022 right here.

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

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

  1. Launch the Visible Studio 2022 Preview IDE.
  2. Click on on “Create new undertaking.”
  3. Within the “Create new undertaking” window, choose “ASP.NET Core Net API” from the listing of templates displayed.
  4. Click on Subsequent.
  5. Within the “Configure your new undertaking” window, specify the identify and site for the brand new undertaking.
  6. Optionally examine the “Place resolution and undertaking in the identical listing” examine field, relying in your preferences.
  7. Click on Subsequent.
  8. Within the “Extra Data” window proven subsequent, uncheck the examine field that claims “Use controllers…” since we’ll be utilizing minimal APIs on this instance. Depart the “Authentication Sort” as “None” (default).
  9. Be certain 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 undertaking 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 customers of CancellationTokens are notified accordingly. Moreover, the IsCancellationRequested property of the cancellation token occasion is ready to true, indicating that the CancellationTokenSource has been canceled and cancellation of the duty has been requested.

You should utilize a CancellationToken to cease an extended working operation when the consumer cancels a request within the internet browser. In different phrases, utilizing a CancellationToken can assist you cease lengthy working requests from utilizing sources when the consumer has stopped or refreshed the net web page.

You should utilize CancellationTokens to cease async duties as effectively. In an async process, cancellation signifies that the duty ought to stop performing its present exercise. An async process 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 internet purposes, you may 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.

Ultimately, the thing 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 needs to be famous that each one lengthy working operations should respect the cancellation request and cancel the lengthy working operations in order that sources might be launched.

Listening for cancellation requests in ASP.NET Core

You’ll be able to hear for cancellation requests by polling the worth of the CancellationToken.IsCancellationRequested property as proven within the code snippet given beneath.

whereas(!cancellationToken.IsCancellationRequested)
{
     //Write your code right here to carry out some operation
}

One other strategy to hear for cancellation requests is to name the ThrowIfCancellationRequested technique, as proven within the code snippet given beneath.

whereas(true)
{
     //Write your code right here to carry out some operation
     cancellationToken.ThrowIfCancellationRequested();
}

And you may hear for cancellation requests by registering a callback as proven within the following code snippet.

WebClient webClient = new WebClient();   
cancellationToken.Register(() =>
{
    webClient.CancelAsync();
});

Create a minimal API handler in ASP.NET Core

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

app.MapGet("/howdy", 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";
});

Whenever you execute this software and hit the /howdy endpoint, you will note that the handler executes in its entirety even in the event you attempt to cease the request by refreshing the net 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("/howdy", 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 whenever you execute the applying and hit the /howdy endpoint, refreshing the net browser earlier than the request completes will cease the request. You’ll see from the logs that the request by no means completes. As an alternative, a TaskCancelledException can be thrown as a result of the CancellationToken.IsCancellationRequested property can be set to true.

The exception messages will comprise the hint data 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 may usually wish to know if cancellation has been requested on a cancellation token. You’ll be able to examine the cancellation state by analyzing the IsCancellationRequested property. The IsCancellationRequested property can 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 observe, however it isn’t at all times really helpful 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 sources, when stopping the request is not going to have any unwanted side effects.

Lastly, for the needs of this text, we used Activity.Delay to simulate an extended working operation. As a substitute, you may substitute any lengthy working calls particular to your software’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.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments