ASP.NET Core MVC Interview Question #48
Why should CancellationToken be passed from MVC actions to services?
Controllers, Actions, Model Binding & Action Results Junior Beginner
Quick Interview Answer
ASP.NET Core exposes a cancellation token that is signaled when the HTTP request is aborted. Passing it to asynchronous database, HTTP, and application-service operations allows unnecessary work to stop when supported.
Detailed Explanation
ASP.NET Core exposes a cancellation token that is signaled when the HTTP request is aborted. Passing it to asynchronous database, HTTP, and application-service operations allows unnecessary work to stop when supported.
The token should be propagated through the call chain rather than created independently inside each method. Cancellation improves resource usage but does not replace sensible timeouts or efficient operations.
Code Example
public async Task<IActionResult> Index(
CancellationToken cancellationToken)
{
var products = await _service
.GetProductsAsync(cancellationToken);
return View(products);
}