- Published on
CancellationTokenSource with Timeout in C# (Part 1)
- Authors

- Name
- Mathias Hove
- @mathias_hove
Why?
Timeouts are a fundamental part of building reliable distributed systems. In ASP.NET Core, they appear everywhere: HTTP requests, database calls, third-party APIs, background jobs, and message handlers.
This short post focuses on how cancellation are used in ASP.NET Core and how to apply timeouts using CancellationTokenSource.
The Request Token
Every ASP.NET Core request exposes a built-in CancellationToken:
HttpContext.RequestAborted
This token is cancelled when:
- The client disconnects
- The request times out at the server or proxy
- The request pipeline is aborted
Passing this token through your application ensures that work stops as soon as it is no longer needed.
Basic Controller Example
[HttpGet("/data")]
public async Task<IActionResult> GetData(CancellationToken cancellationToken)
{
await _service.FetchAsync(cancellationToken);
return Ok();
}
ASP.NET Core automatically binds the request token when it is declared as a parameter.
Adding a Timeout Inside ASP.NET Core
Often, you want both:
- Awareness of client disconnects
- A maximum execution time for e.g. a service where you are fetching data.
This is where CancellationTokenSource with a timeout becomes useful.
[HttpGet("/data")]
public async Task<IActionResult> GetData(CancellationToken requestToken)
{
using var timeoutCts =
new CancellationTokenSource(TimeSpan.FromSeconds(5));
using var linkedCts =
CancellationTokenSource.CreateLinkedTokenSource(
timeoutCts.Token,
requestToken);
await _service.FetchAsync(linkedCts.Token);
return Ok();
}
We are basically linking the original cancellation token, with the timeout cancellation token source by calling CreateLinkedTokenSource. This gives us the possibility cancel an operation if either the client disconnects or the timeout expires.
Catching Exception instead of OperationCanceledException
catch (Exception)
{
// Cancellation semantics are lost
}
Cancellation is not an error condition and should be handled explicitly.
Summary
- ASP.NET Core provides a request-scoped cancellation token
- Timeouts should be implemented using
CancellationTokenSource - Always link tokens. Do not replace.
- Cancellation should propagate through the entire call chain
In Part 2, we’ll compare this approach with HttpClient.Timeout