ASP.NET Core Web API Interview Question #110
Why should CancellationToken be accepted by API operations?
Dependency Injection, Services, EF Core, Async & Data Access Mid-Level Intermediate
Quick Interview Answer
A CancellationToken lets work observe that the request has been cancelled, for example because the client disconnected or an upstream timeout occurred. Passing the token into EF Core and other asynchronous I/O can avoid wasting resources on work whose result is no longer needed.
Detailed Explanation
A CancellationToken lets work observe that the request has been cancelled, for example because the client disconnected or an upstream timeout occurred. Passing the token into EF Core and other asynchronous I/O can avoid wasting resources on work whose result is no longer needed.
Cancellation should be propagated through the call chain rather than accepted by the controller and then ignored.
Code Example
[HttpGet("{id:int}")]
public async Task<ActionResult<ProductResponse>> Get(
int id,
CancellationToken cancellationToken)
{
var item = await _service.GetAsync(id, cancellationToken);
return item == null ? NotFound() : Ok(item);
}