Interview frequency: …
Short answer
Accept it in Controller parameters and pass it through to every async method and database call, cancelling operations and freeing resources as soon as the client closes the browser.
Explanation
If a user requests a report that takes 30 seconds and closes the page after two seconds, failing to pass a CancellationToken makes the server continue querying and calculating needlessly. Accept CancellationToken cancellationToken in the Action and pass it to ToListAsync(cancellationToken); this stops the SQL query when the client disconnects and throws OperationCanceledException to release resources immediately.
Code example
[HttpGet("export")]
public async Task<IActionResult> Export(CancellationToken ct) {
var data = await db.Reports.ToListAsync(ct); // Stops immediately if the user closes the browser
return Ok(data);
}Common mistakes
- Catching and suppressing OperationCanceledException as an ordinary error, treating it as an unexpected server error 500.
Follow-up questions
- How do you process asynchronous work in parallel with Parallel.ForEachAsync in .NET 6+?
- What is IAsyncEnumerable<T>, and how does it stream large result sets in ASP.NET Core?