.NET 4 minute read

Cancellation Tokens in .NET: A Small Detail With Real Consequences

How to propagate request cancellation in ASP.NET Core without confusing cancellation with timeouts or application errors.

When an HTTP client disconnects, ASP.NET Core exposes a cancellation token through HttpContext.RequestAborted. If your application performs slow I/O but ignores cancellation, it may continue spending resources on work the caller no longer needs.

Passing a cancellation token is not about making every operation magically cancellable. It gives supporting APIs an opportunity to stop cooperatively.

Propagate the token through the layers

In a Minimal API handler, the framework can bind a CancellationToken parameter to the request cancellation token:

app.MapGet("/orders/{id:int}", async (
    int id,
    IOrderRepository repository,
    CancellationToken cancellationToken) =>
{
    var order = await repository.GetByIdAsync(id, cancellationToken);
    return order is null ? Results.NotFound() : Results.Ok(order);
});

The repository should pass the token onward to the underlying asynchronous I/O operation when the API supports it.

Cancellation is not a timeout

RequestAborted represents the lifetime of the HTTP request. A business-level timeout is a separate constraint. You can link a timeout token to the request token when an operation must not exceed a defined duration, but the two reasons for cancellation are different.

When logging, distinguish a client cancellation from a server timeout or an unexpected exception. An expected cancellation usually should not be reported as an application failure.

Be careful with side effects

Cancellation is cooperative and is not a distributed rollback mechanism. If a payment, event publish or database transaction has already committed, cancelling the task does not undo it. Design side effects with clear transactional and idempotency boundaries.

The principle: pass cancellation through I/O boundaries, measure abandoned work, and treat side effects deliberately.

Have a similar challenge?

I work with teams on .NET architecture, Azure cloud and applied AI integration.

Let's talk ↗