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

How to use cancellation tokens in ASP.NET Core 7

While ASP.Net Main 7 is the latest variation of Microsoft’s open resource web software development framework, it requires edge of plenty of substantial functions from previous variations of .Net. One particular of these sizeable capabilities is cancellation tokens, which present a way of gracefully dealing with multi-threaded apps.

When doing the job with ASP.Net Main applications, it is great follow to make extensive managing operations (this sort of as a database question or track record system) cancelable, either soon after a specific size of time or on person ask for, so that the application can launch sources and remain responsive. Here’s in which cancellation tokens appear into play.

This article discusses cancellation tokens, why they are beneficial, and how to use them in nominal API handlers in ASP.Internet Core. To do the job with the code examples delivered in this short article, you should really have Visual Studio 2022 Preview set up in your system. If you don’t currently have a copy, you can down load Visual Studio 2022 here.

Produce an ASP.Web Main 7 negligible World wide web API project in Visual Studio 2022

To start with off, let us generate an ASP.Net Core minimum API job in Visible Studio. Following these methods will produce a new ASP.Internet Core 7 World wide web API undertaking in Visible Studio 2022 Preview:

  1. Launch the Visual Studio 2022 Preview IDE.
  2. Click on on “Create new project.”
  3. In the “Create new project” window, find “ASP.Internet Core Net API” from the listing of templates shown.
  4. Click Future.
  5. In the “Configure your new project” window, specify the identify and spot for the new task.
  6. Optionally check out the “Place remedy and project in the same directory” check box, relying on your tastes.
  7. Click on Upcoming.
  8. In the “Additional Information” window proven subsequent, uncheck the examine box that claims “Use controllers…” considering that we’ll be using nominal APIs in this case in point. Go away the “Authentication Type” as “None” (default).
  9. Ensure that the verify containers “Enable Docker,” “Configure for HTTPS,” and “Enable Open API Support” are unchecked as we will never be working with any of all those options here.
  10. ClickCreate.

We are going to use this ASP.Web Main 7 Internet API task to generate nominal API endpoints and work with cancellation tokens.

What are cancellation tokens? When must we use them?

A CancellationToken is a lightweight item created by a CancellationTokenSource instance. When a CancellationTokenSource is canceled, all customers of CancellationTokens are notified accordingly. Furthermore, the IsCancellationRequested property of the cancellation token instance is established to correct, indicating that the CancellationTokenSource has been canceled and cancellation of the job has been requested.

You can use a CancellationToken to halt a very long operating operation when the person cancels a request in the website browser. In other terms, applying a CancellationToken can assistance you quit long functioning requests from employing means when the person has stopped or refreshed the website website page.

You can use CancellationTokens to halt async duties as nicely. In an async job, cancellation suggests that the undertaking ought to stop undertaking its present-day exercise. An async activity gets a cancellation token and examines it to see if a cancellation is requested. If so, the present procedure must stop promptly.

Long managing requests in ASP.Internet Main

When working on world-wide-web applications, you could generally make use of extended operating jobs, ie, databases phone calls, file handling, and so on. When an object generates one or a lot more prolonged managing functions, it need to pass cancellation tokens to all of all those functions. Cancellation tokens must also be passed to other inside operations.

Eventually, the object that made the extensive operating functions could — following a time deadline is attained, or when a user stops a request — propagate a cancellation notification to these cancellation tokens. It really should be famous that all extended managing operations need to regard the cancellation ask for and terminate the lengthy working functions so that means can be released.

Listening for cancellation requests in ASP.Net Main

You can listen for cancellation requests by polling the price of the CancellationToken.IsCancellationRequested house as demonstrated in the code snippet offered underneath.

even though(!cancellationToken.IsCancellationRequested)

     //Produce your code here to accomplish some operation

Yet another way to listen for cancellation requests is to contact the ThrowIfCancellationRequested approach, as demonstrated in the code snippet given down below.

even though(true)

     //Generate your code in this article to accomplish some operation

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

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


Develop a minimum API handler in ASP.Web Main

Let’s now simulate a prolonged managing request and see how cancellation will work. To start with we are going to test a prolonged working ask for with no cancellation. Create the following piece of code in the Program.cs file.

application.MapGet("/hi", async () =>

    app.Logger.LogInformation("Ask for started out at: "+DateTime.Now.ToLongTimeString())
    await Task.Delay(TimeSpan.FromSeconds(5))
    app.Logger.LogInformation("Ask for done at: " + DateTime.Now.ToLongTimeString())
    return "Results"

When you execute this software and hit the /hello endpoint, you will see that the handler executes in its entirety even if you try to quit the request by refreshing the website browser as shown in Figure 1.

cancellation tokens 01 IDG

Determine 1: Without the need of cancellation, the handler executes in its entirety even if the request is aborted by the consumer.

Use a CancellationToken in a nominal API handler

The adhering to code listing displays how you can inject a CancellationToken into our endpoint handler and pass this token to the Job.Hold off technique.

application.MapGet("/hello", async (CancellationToken token) =>

    application.Logger.LogInformation("Ask for started off at: " + DateTime.Now.ToLongTimeString())
    await Job.Delay(TimeSpan.FromSeconds(5), token)
    application.Logger.LogInformation("Request done at: " + DateTime.Now.ToLongTimeString())
    return "Results"

Now when you execute the application and hit the /good day endpoint, refreshing the world-wide-web browser before the request completes will end the request. You’ll see from the logs that the ask for by no means completes. Alternatively, a TaskCancelledException will be thrown for the reason that the CancellationToken.IsCancellationRequested home will be established to true.

The exception messages will consist of the trace information on the aborted request as demonstrated in Figure 2.

cancellation tokens 02 IDG

Figure 2: When cancellation has been applied in the handler code, a request that is aborted midway will not complete.

Examining cancellation point out in ASP.Net Core

You might typically want to know if cancellation has been requested on a cancellation token. You can look at the cancellation state by inspecting the IsCancellationRequested house. The IsCancellationRequested residence will be legitimate (ie, will have a boolean value of true) if cancellation has been requested on the token, phony if not.

As described above, the CancellationToken.ThrowIfCancellationRequested method will throw an OperationCanceledException if the cancellation token occasion has asked for cancellation.

The adhering to code snippet illustrates how the IsCancellationRequested house can be employed to check out if the token has requested cancellation. If the request has been cancelled, an occasion of OperationCanceledException is thrown.

if (token.IsCancellationRequested)

    application.Logger.LogInformation("Request has been cancelled..")
    throw new OperationCanceledException()

Using cancellation tokens is a fantastic apply, but it is not always recommended in your controller action approaches. If the request modifies the state, you will not want such a ask for to be cancelled. Cancellation tokens are valuable largely for extended operating calls that eat substantial assets, when stopping the request will not have any facet results.

Lastly, for the reasons of this write-up, we made use of Activity.Delay to simulate a very long jogging operation. In its put, you can substitute any long functioning calls certain to your application’s needs these kinds of as databases calls, community calls, file handling operations, downloading documents from the online, and so on.

Copyright © 2022 IDG Communications, Inc.

Leave a Reply