ASP.NET Core Interview Question #165
Why is CancellationToken important in ASP.NET Core?
Logging, Error Handling & Background Services Mid-Level Intermediate
Quick Interview Answer
CancellationToken allows asynchronous operations to stop cooperatively when work is no longer required. In HTTP processing, RequestAborted can signal that the client disconnected. In hosted services, the stopping token signals application shutdown.
Detailed Explanation
CancellationToken allows asynchronous operations to stop cooperatively when work is no longer required. In HTTP processing, RequestAborted can signal that the client disconnected. In hosted services, the stopping token signals application shutdown.
Passing cancellation tokens through database, HTTP, delay, and other asynchronous operations can free resources sooner and improve graceful shutdown behavior.
Cancellation is cooperative: code and the APIs it calls must observe the token for cancellation to take effect.
Code Example
[HttpGet]
public async Task<IActionResult> Get(
CancellationToken cancellationToken)
{
var products = await _service
.GetProductsAsync(cancellationToken);
return Ok(products);
}