AspNetCoreDiagnosticScenarios
AspNetCoreDiagnosticScenarios copied to clipboard
Mapping CancellationToken in controller's actions
We often see code like that
public async Task<IActionResult> Get()
{
await Task.Delay(1000);
return View();
}
Is it a good practice to add the CancellationToken parameter to actions when it goes async and pass this parameter to async methods ?
public async Task<IActionResult> Get(int id, CancellationToken cancellationToken)
{
await Task.Delay(1000, cancellationToken);
return View();
}
Exactly right, you can think about it. For example, at this point, your asynchronous operation is a long task in the background and it may take up to 60 seconds to return. But the user thinks I can't wait any longer and quits immediately before the 60 seconds This cancellation would be triggered at this point, and then the long background task would also be canceled, saving server resources. Of course in the vast majority of cases there will be no such extra-long tasks, but adding this optimization is sometimes necessary. As the saying goes, a little goes a long way.