Search code examples
c#asynchronoustaskcancellation-token

Should I pass a CancellationToken to Task.Run?


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?


Solution

  • 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.