Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mapping CancellationToken in controller's actions #79

Open
juchom opened this issue Sep 29, 2021 · 1 comment
Open

Mapping CancellationToken in controller's actions #79

juchom opened this issue Sep 29, 2021 · 1 comment

Comments

@juchom
Copy link

juchom commented Sep 29, 2021

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
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants