In a high-pressure Web API, users often cancel requests (by closing the browser tab or hitting refresh). If your server continues to process a 30-second report for a user who is no longer there, you are wasting CPU and DB resources. CancellationTokens allow you to stop "Ghost Requests" instantly.
Cancellation in .NET is Cooperative. You cannot "violently" kill a thread from the outside (that's dangerous). Instead, you pass a token to the method, and the method periodically checks: "Has someone asked me to stop?"
public async Task ProcessData(CancellationToken ct)
{
foreach(var item in items)
{
// Check if the user cancelled
ct.ThrowIfCancellationRequested();
await DoWork(item, ct); // Pass the token deep into the next method!
}
}
You can create a token that automatically "fires" after a certain number of seconds, providing a clean way to implement timeouts without complex timer logic.
var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
try
{
await LongMethod(cts.Token);
}
catch (OperationCanceledException)
{
Console.WriteLine("Task took too long and was aborted!");
}
Q: "Why should I pass a CancellationToken all the way down to EF Core or HttpClient methods?"
Architect Answer: "To prevent Resource Leaks. If you fire a massive SQL query but the user cancels the HTTP request, and you DON'T pass the token to EF Core, the SQL Server will continue working for minutes, wasting memory and potentially locking tables for a result that will literally be thrown in the trash when it returns to C#. By passing the token, EF Core actually sends a 'Cancel' signal to the SQL Server, killing the remote process immediately. It is the single most effective way to improve the 'Stability' of a high-traffic system."