Cooperative Cancellation in ASP.NET Core: Stop Wasteful Work and Protect Resources

Cooperative Cancellation in ASP.NET Core: Stop Wasteful Work and Protect Resources

An HTTP request can end before the server finishes producing its response. A user may close a page, a mobile connection may disappear, a client may time out, or a proxy may terminate the request. If the application continues running a database query, downstream HTTP call, or expensive calculation, it consumes CPU, memory, connection-pool capacity, and external service capacity for work nobody will use.

The core solution is .NET’s cooperative cancellation model based on CancellationToken. Cancellation is not forced onto running code. One component publishes a cancellation request, while the operation being performed observes that request and stops at an appropriate point. In ASP.NET Core, request cancellation is represented by HttpContext.RequestAborted. Hosted services receive a separate token from the host for graceful shutdown.

How cooperative cancellation works

The pattern has three parts:

  1. A CancellationTokenSource manages the cancellation request.
  2. A CancellationToken obtained from that source is passed to cancellable operations.
  3. The operation observes the token directly or forwards it to APIs that support cancellation.

Passing a token does not automatically stop work. A method can accept a token and still ignore it. Effective cancellation therefore needs to flow from the entry point through service and data-access layers to the lowest-level operation that can actually stop.

Using RequestAborted for HTTP requests

HttpContext.RequestAborted provides notification when the connection underlying the request is aborted. Minimal APIs can bind this token directly to a CancellationToken parameter:

app.MapGet("/reports/{id}", async (int id, CancellationToken cancellationToken, IReportService reports) =>
{
    var report = await reports.GetAsync(id, cancellationToken);
    return report is null ? Results.NotFound() : Results.Ok(report);
});

In a controller or middleware, use HttpContext.RequestAborted explicitly:

[HttpGet("{id:int}")]
public async Task<IActionResult> Get(int id)
{
    var result = await service.GetAsync(id, HttpContext.RequestAborted);
    return result is null ? NotFound() : Ok(result);
}

The token should normally be passed to the asynchronous operations that retrieve the response content. Request-body reads already fail when the request is aborted, and response writes generally become no-ops after the connection is gone. The most important optimization is usually stopping the work that prepares the response.

Flow the token into data access

Database access is one of the most valuable places to apply cancellation. EF Core query methods expose cancellation-aware overloads. When the provider supports cancellation, the database operation can be asked to stop after the client no longer needs the result.

public async Task<OrderDto?> GetAsync(
    int orderId,
    CancellationToken cancellationToken)
{
    return await dbContext.Orders
        .Where(order => order.Id == orderId)
        .Select(order => new OrderDto(order.Id, order.Total))
        .SingleOrDefaultAsync(cancellationToken);
}

The service does not create a new token. It accepts the caller’s token and forwards it. This keeps the same service usable from an HTTP request, a scheduled process, a command-line operation, or a test.

Make HttpClient calls cancellable

If an endpoint calls another API, propagate request cancellation to that downstream call. Otherwise, the incoming request may finish while the outgoing operation continues in the background.

public async Task<CatalogItem?> GetItemAsync(
    string id,
    CancellationToken cancellationToken)
{
    using var response = await httpClient.GetAsync(
        $"catalog/{id}",
        cancellationToken);

    response.EnsureSuccessStatusCode();
    return await response.Content.ReadFromJsonAsync<CatalogItem>(
        cancellationToken: cancellationToken);
}

Prefer overloads that accept a token throughout the call chain. If a third-party API has no cancellation support, adding a token to your own method signature does not make that underlying operation cancellable. Avoid wrapping blocking work in another thread merely to create the appearance of cancellation; the blocking operation may still consume resources.

Treat cancellation differently from failures

Cancellation is often expected control flow. Cancellable .NET operations can throw OperationCanceledException or TaskCanceledException. Logging every request cancellation as an application error can create misleading alerts and noisy telemetry.

try
{
    var data = await service.LoadAsync(
        HttpContext.RequestAborted);
    return Ok(data);
}
catch (OperationCanceledException) when (
    HttpContext.RequestAborted.IsCancellationRequested)
{
    // The client is no longer waiting for this response.
    return new EmptyResult();
}

If the application has centralized exception handling, define how cancellation should be represented there. Trying to write a detailed error response after the connection has closed is usually ineffective. Cancellation events can still be counted separately for operational visibility.

Observe cancellation in custom loops

CPU-bound or incremental application code must check the token periodically. ThrowIfCancellationRequested throws an OperationCanceledException associated with the requested cancellation.

public static async Task<long> CalculateAsync(
    IReadOnlyCollection<int> values,
    CancellationToken cancellationToken)
{
    long total = 0;

    foreach (var value in values)
    {
        cancellationToken.ThrowIfCancellationRequested();
        total += ExpensiveCalculation(value);
        await Task.Yield();
    }

    return total;
}

Choose a check frequency based on the cost of each unit of work. Checking too often can add overhead to tiny operations; checking too rarely delays shutdown. The practical goal is a reasonable balance between cancellation responsiveness and processing cost.

Request cancellation and timeouts are different

RequestAborted indicates that the request is no longer usable. A business or infrastructure timeout is a separate policy. For example, an external service may be allowed to run for at most two seconds. Combine the request token with a timeout token:

using var timeoutCts = new CancellationTokenSource(
    TimeSpan.FromSeconds(2));
using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(
    HttpContext.RequestAborted,
    timeoutCts.Token);

var result = await client.GetAsync(
    "slow-endpoint",
    linkedCts.Token);

The operation can now stop when either the client disconnects or the timeout expires. If those causes must be distinguished, keep the original tokens available for diagnostics or apply a dedicated timeout policy.

Handle BackgroundService shutdown correctly

The token supplied to ExecuteAsync is cancelled when the host begins stopping the background service. The service should observe it and return promptly so the application can complete a graceful shutdown.

public sealed class QueueWorker(
    IWorkQueue queue,
    ILogger<QueueWorker> logger) : BackgroundService
{
    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            var workItem = await queue.DequeueAsync(stoppingToken);

            try
            {
                await workItem(stoppingToken);
            }
            catch (OperationCanceledException)
                when (stoppingToken.IsCancellationRequested)
            {
                break;
            }
            catch (Exception exception)
            {
                logger.LogError(exception, "Work item failed.");
            }
        }
    }
}

Pass the stopping token to queue waits, delays, database calls, and downstream requests whenever those APIs support cancellation. During shutdown, stop accepting new work and allow active work to reach a safe boundary. This is especially important when a work item changes durable state.

The host waits for hosted services to stop within its configured shutdown window. A service that ignores the token can delay graceful shutdown and may eventually be stopped non-gracefully when the window expires.

Practical design rules

  • Place CancellationToken as the final parameter of long-running asynchronous methods.
  • Forward the caller’s token instead of creating unrelated tokens in every layer.
  • Use cancellation-aware overloads in framework, database, and HTTP APIs.
  • Separate expected cancellation from failure metrics and alerting.
  • Review transactions and idempotency for writes that can be interrupted.
  • Ensure every BackgroundService loop observes its stopping token.
  • Test cancellation while a database query, downstream request, queue wait, and custom loop are active.

Conclusion

Cooperative cancellation is more than an optional parameter. It is a design contract that controls resource usage, request responsiveness, and application shutdown behavior. Propagating RequestAborted into database and downstream HTTP operations helps stop work that is no longer needed. Applying the same principle to BackgroundService makes deployments, restarts, and scale operations more predictable.

Sources

//

0 Comments

Write Comment

E-Mail address will not be published