CancellationToken in ASP.NET Core

Introduction

In the realm of asynchronous programming, ensuring responsiveness and graceful termination of operations is crucial for building robust and efficient applications. CancellationToken in ASP.NET Core provides a powerful mechanism for achieving this goal. In this article, we will delve into the concept of CancellationToken, its usage, and practical examples to illustrate its importance in asynchronous programming.

What is CancellationToken?

CancellationToken is a type in ASP.NET Core used for cooperative cancellation between threads or components. It allows you to signal to asynchronous operations that they should be canceled, providing a way to gracefully terminate ongoing tasks.

Understanding the Components

  • CancellationToken: Represents the ability to cancel an operation. It is passed to methods performing asynchronous operations to check for cancellation requests.
  • CancellationTokenSource: Creates and controls the CancellationToken. It is used to issue cancellation requests to the associated CancellationToken.

Usage and Examples

1. Creating a CancellationToken

CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationToken cancellationToken = cancellationTokenSource.Token;

2. Passing CancellationToken to Methods

public async Task SomeAsyncOperation(CancellationToken cancellationToken)
{
    while (!cancellationToken.IsCancellationRequested)
    {
        // Do some work
        
        // Check for cancellation
        cancellationToken.ThrowIfCancellationRequested();
        
        // Continue work
    }
}

3. Cancelling the Operation

cancellationTokenSource.Cancel();

4. Handling Cancellation

if (cancellationToken.IsCancellationRequested)
{
    // Clean up and exit operation
    return;
}

Practical Example

using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace YourNamespace.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DataController : ControllerBase
    {
        private readonly HttpClient _httpClient;

        public DataController()
        {
            _httpClient = new HttpClient();
        }

        [HttpGet]
        public async Task<IActionResult> FetchData(CancellationToken cancellationToken)
        {
            try
            {
                // Make an asynchronous call to an external API
                var response = await _httpClient.GetAsync("https://api.example.com/data", cancellationToken);
                
                // Ensure the response is successful
                response.EnsureSuccessStatusCode();
                
                // Read the response content
                var data = await response.Content.ReadAsStringAsync();
                
                return Ok(data);
            }
            catch (OperationCanceledException)
            {
                // Cancellation requested
                return StatusCode(500, "Request cancelled.");
            }
            catch (HttpRequestException ex)
            {
                // Error occurred during HTTP request
                return StatusCode(500, $"Error: {ex.Message}");
            }
        }
    }
}

Remark

A CancellationToken enables cooperative cancellation between threads, thread pool work items, or Task objects. You create a cancellation token by instantiating a CancellationTokenSource object, which manages cancellation tokens retrieved from its CancellationTokenSource.Token property. You then pass the cancellation token to any number of threads, tasks, or operations that should receive notice of cancellation. The token cannot be used to initiate cancellation. When the owning object calls CancellationTokenSource.Cancel the IsCancellationRequested property on every copy of the cancellation token is set to true. The objects that receive the notification can respond in whatever manner is appropriate.

Conclusion

In the world of asynchronous programming, CancellationToken plays a vital role in managing and controlling asynchronous operations. By leveraging CancellationToken, developers can ensure responsiveness, graceful termination, and improved resource management in their ASP.NET Core applications. Understanding its usage and incorporating it into your asynchronous workflows can significantly enhance the reliability and performance of your applications.

Reference: https://learn.microsoft.com/en-us/dotnet/api/system.threading.cancellationtoken?view=net-8.0


Similar Articles