AspNetCoreDiagnosticScenarios icon indicating copy to clipboard operation
AspNetCoreDiagnosticScenarios copied to clipboard

Mapping CancellationToken in controller's actions

Open juchom opened this issue 2 years ago • 1 comments

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();
}

juchom avatar Sep 29 '21 15:09 juchom

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.

newbe36524 avatar Sep 30 '21 01:09 newbe36524