davidfowl / AspNetCoreDiagnosticScenarios

This repository has examples of broken patterns in ASP.NET Core applications
7.65k stars 736 forks source link

Mapping CancellationToken in controller's actions #79

Open juchom opened 2 years ago

juchom commented 2 years ago

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();
}
newbe36524 commented 2 years ago

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.