CancellationToken
in an ASP.NET Web ApplicationCancellationToken
is a feature in .NET that allows tasks to be cancelled gracefully. It is particularly useful in ASP.NET applications where requests may need to be terminated due to user actions, timeouts, or resource limitations. Learn More
CancellationToken
?Improve Performance – Prevent unnecessary resource consumption when a request is abandoned.
Handle User Actions – Allow cancellation if a user navigates away or closes the browser.
Support Long-Running Processes – Cancel background tasks when no longer needed.
When handling HTTP requests in ASP.NET Core, you can pass CancellationToken
as a parameter:
csharp
[HttpGet("long-operation")]
public async Task<IActionResult> PerformLongOperation(CancellationToken cancellationToken)
{
try
{
// Simulate a long-running task
await Task.Delay(5000, cancellationToken);
return Ok("Operation completed successfully");
}
catch (OperationCanceledException)
{
return StatusCode(499, "Client closed the request");
}
}
CancellationToken
in Background ServicesIf you are running background tasks (e.g., fetching data periodically), use CancellationToken
in services:
csharp
public class MyBackgroundService : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
// Perform periodic work
await Task.Delay(1000, stoppingToken);
}
}
}
Always check cancellationToken.IsCancellationRequested
inside loops or long-running tasks.
Catch OperationCanceledException
to gracefully handle task cancellation.
Inject CancellationToken
in async methods whenever applicable.