yes no neon sign cancel buzzwords just say no red neon by sarawuth702 getty

Despite the fact that ASP.Web Core 7 is the newest edition of Microsoft’s open source internet software advancement framework, it can take benefit of many sizeable functions from earlier versions of .Net. One particular of these sizeable attributes is cancellation tokens, which supply a way of gracefully managing multi-threaded applications.

When doing work with ASP.Web Main programs, it is fantastic exercise to make prolonged operating operations (these kinds of as a database query or background procedure) cancelable, both just after a specific size of time or upon user request, so that the software can release assets and keep on being responsive. Here’s the place cancellation tokens occur into engage in.

This report discusses cancellation tokens, why they are useful, and how to use them in minimal API handlers in ASP.Net Main. To work with the code examples presented in this short article, you must have Visual Studio 2022 Preview mounted in your program. If you really do not already have a duplicate, you can download Visible Studio 2022 here.

Develop an ASP.Net Core 7 small World-wide-web API undertaking in Visual Studio 2022

To start with off, let us produce an ASP.Internet Main negligible API challenge in Visual Studio. Subsequent these ways will develop a new ASP.Net Core 7 World-wide-web API challenge in Visible Studio 2022 Preview:

  1. Start the Visual Studio 2022 Preview IDE.
  2. Simply click on “Create new challenge.”
  3. In the “Create new project” window, select “ASP.Net Core Net API” from the list of templates shown.
  4. Click Up coming.
  5. In the “Configure your new project” window, specify the name and area for the new venture.
  6. Optionally verify the “Place solution and undertaking in the exact same directory” examine box, relying on your tastes.
  7. Simply click Next.
  8. In the “Additional Information” window proven next, uncheck the check out box that claims “Use controllers…” considering that we’ll be applying minimum APIs in this case in point. Go away the “Authentication Type” as “None” (default).
  9. Assure that the verify bins “Enable Docker,” “Configure for HTTPS,” and “Enable Open up API Support” are unchecked as we will not be utilizing any of all those capabilities listed here.
  10. Click on Create.

We’ll use this ASP.Internet Main 7 Website API venture to create minimum API endpoints and function with cancellation tokens.

What are cancellation tokens? When must we use them?

A CancellationToken is a lightweight item established by a CancellationTokenSource instance. When a CancellationTokenSource is canceled, all consumers of CancellationTokens are notified appropriately. Furthermore, the IsCancellationRequested house of the cancellation token instance is established to genuine, indicating that the CancellationTokenSource has been canceled and cancellation of the task has been requested.

You can use a CancellationToken to cease a prolonged working operation when the user cancels a request in the internet browser. In other words, applying a CancellationToken can aid you halt extended working requests from applying assets when the consumer has stopped or refreshed the internet webpage.

You can use CancellationTokens to stop async jobs as properly. In an async activity, cancellation implies that the process should cease executing its present-day action. An async job receives a cancellation token and examines it to see if a cancellation is requested. If so, the latest operation really should stop right away.

Extended running requests in ASP.Web Main

When performing on web programs, you may generally make use of prolonged managing tasks, i.e., databases phone calls, file managing, etc. When an object produces 1 or far more prolonged functioning functions, it really should move cancellation tokens to all of people functions. Cancellation tokens should really also be handed to other inner operations.

Inevitably, the item that created the long functioning functions may well — after a time deadline is achieved, or when a consumer stops a request — propagate a cancellation notification to these cancellation tokens. It really should be mentioned that all extensive running operations should regard the cancellation request and cancel the extensive functioning operations so that assets can be introduced.

Listening for cancellation requests in ASP.Web Main

You can listen for cancellation requests by polling the value of the CancellationToken.IsCancellationRequested residence as shown in the code snippet specified under.

even though(!cancellationToken.IsCancellationRequested)

     //Publish your code below to perform some operation

One more way to listen for cancellation requests is to simply call the ThrowIfCancellationRequested system, as proven in the code snippet provided below.


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

And you can hear for cancellation requests by registering a callback as shown in the adhering to code snippet.

WebClient webClient = new WebClient()   
cancellationToken.Sign up(() =>


Make a minimum API handler in ASP.Internet Core

Let’s now simulate a lengthy managing ask for and see how cancellation works. 1st we’ll try out a long working request without the need of cancellation. Publish the pursuing piece of code in the System.cs file.

app.MapGet("/hi there", async () =>

    application.Logger.LogInformation("Ask for begun at: "+DateTime.Now.ToLongTimeString())
    await Endeavor.Hold off(TimeSpan.FromSeconds(5))
    application.Logger.LogInformation("Ask for finished at: " + DateTime.Now.ToLongTimeString())
    return "Achievements"

When you execute this application and strike the /good day endpoint, you will see that the handler executes in its entirety even if you check out to cease the request by refreshing the internet browser as revealed in Determine 1.

cancellation tokens 01 IDG

Determine 1: Without having cancellation, the handler executes in its entirety even if the request is aborted by the person.

Use a CancellationToken in a minimal API handler

The pursuing code listing reveals how you can inject a CancellationToken into our endpoint handler and pass this token to the Activity.Hold off technique.

app.MapGet("/hi", async (CancellationToken token) =>

    application.Logger.LogInformation("Ask for begun at: " + DateTime.Now.ToLongTimeString())
    await Activity.Hold off(TimeSpan.FromSeconds(5), token)
    app.Logger.LogInformation("Request completed at: " + DateTime.Now.ToLongTimeString())
    return "Achievement"

Now when you execute the application and strike the /good day endpoint, refreshing the world-wide-web browser ahead of the request completes will halt the request. You are going to see from the logs that the request hardly ever completes. In its place, a TaskCancelledException will be thrown due to the fact the CancellationToken.IsCancellationRequested assets will be established to true.

The exception messages will comprise the trace data on the aborted ask for as demonstrated in Figure 2.

cancellation tokens 02 IDG

Figure 2: When cancellation has been utilized in the handler code, a ask for that is aborted halfway will not total.

Examining cancellation state in ASP.Net Core

You may possibly typically want to know if cancellation has been requested on a cancellation token. You can examine the cancellation condition by examining the IsCancellationRequested assets. The IsCancellationRequested home will be real (i.e., will have a boolean value of accurate) if cancellation has been requested on the token, wrong or else.

As talked about previously mentioned, the CancellationToken.ThrowIfCancellationRequested strategy will toss an OperationCanceledException if the cancellation token instance has asked for cancellation.

The pursuing code snippet illustrates how the IsCancellationRequested house can be made use of to test if the token has asked for cancellation. If the request has been cancelled, an instance of OperationCanceledException is thrown.

if (token.IsCancellationRequested)

    application.Logger.LogInformation("Ask for has been cancelled..")
    toss new OperationCanceledException()

Utilizing cancellation tokens is a good observe, but it is not always encouraged in your controller action techniques. If the request modifies the condition, you will not want such a request to be cancelled. Cancellation tokens are practical mostly for extended operating phone calls that eat significant means, when stopping the ask for will not have any aspect effects.

Last but not least, for the purposes of this post, we utilized Job.Hold off to simulate a extensive functioning operation. In its position, you can substitute any prolonged working calls precise to your application’s necessities these kinds of as databases phone calls, community calls, file dealing with functions, downloading files from the web, and so on.

Copyright © 2022 IDG Communications, Inc.