1

Regarding this example:

return Task.Run(
   async () => {
     while (!stoppingToken.IsCancellationRequested) {
       await Task.Delay(1000);
      }
    }, stoppingToken);

Should I pass the stoppingToken to Task.Run or not? How does this changes the code behavior?

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
k-eight-s
  • 13
  • 2
  • 1
    As a side note you may wanna throw instead, to mark the task as cancelled and stop continuations https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/task-cancellation but that depends on your usecase. – sommmen Dec 14 '21 at 08:13
  • As a side note, if you want the `CancellationToken` to have stopping semantics (as it's evident from the name chosen for the variable `stoppingToken`), you should handle and suppress all `OperationCanceledException`s that may occur. By adding the `stoppingToken` as argument to `Task.Run`, you have one more point to watch for this exception. – Theodor Zoulias Dec 14 '21 at 10:21

1 Answers1

3

If the task is scheduled to run but has not started yet, passing the token will prevent the task from being started if a cancellation is requested before the task is actually started.

See the docs:

A cancellation token that can be used to cancel the work if it has not yet started.

Do mind in your example you could pass the token to Task.Delay as well to minimize the time taken to respond to the cancellation request.

Peter Bons
  • 26,826
  • 4
  • 50
  • 74