How to use cancellation tokens in ASP.NET Core 7

Although ASP.NET Core 7 is the latest version of Microsoft’s open-source web application development framework, it leverages many important features from previous versions of .NET. One such important feature is cancellation tokens, which provide a way to easily handle multithreaded applications.

When working with ASP.NET Core applications, it’s a good practice to kill long-running operations (e.g. a database query or a background process) either after a period of time or at user request so that the application can free up resources and remain responsive. This is where cancellation tokens come into play.

This article explains cancellation tokens, why they’re useful, and how to use them in minimal API handlers in ASP.NET Core. In order to work with the code samples provided in this article, Visual Studio 2022 Preview should be installed on your system. If you don’t already have a copy, you can download Visual Studio 2022 here.

Create a minimal ASP.NET Core 7 Web API project in Visual Studio 2022

First, let’s create a minimal ASP.NET Core API project in Visual Studio. The following steps create a new ASP.NET Core 7 Web API project in Visual Studio 2022 Preview:

  1. Launch the Visual Studio 2022 Preview IDE.
  2. Click on “Create new project”.
  3. In the Create a new project window, select “ASP.NET Core Web API” from the list of templates that appear.
  4. Click next.
  5. In the Configure New Project window, specify the name and location for the new project.
  6. Optionally check the “Place solution and project in the same directory” checkbox based on your preference.
  7. Click next.
  8. In the next Additional Info window, uncheck the “Use Controller…” box as we will be using minimal APIs in this example. Leave the “Authentication Type” as “None” (default).
  9. Make sure the “Enable Docker”, “Configure for HTTPS” and “Enable Open API Support” checkboxes are unchecked as we will not be using any of these features here.
  10. Click Create.

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

What are cancellation tokens? When should we use them?

A CancellationToken is a simple object created by a CancellationTokenSource instance. When a CancellationTokenSource is canceled, all consumers of CancellationTokens are notified accordingly. In addition, the IsCancellationRequested property of the cancellation token instance is set to true, indicating that the CancellationTokenSource was canceled and the task was requested to be canceled.

Copyright © 2022 IDG Communications, Inc.

Leave a Reply

Your email address will not be published. Required fields are marked *