0

The C# method Task.Factory.StartNew takes an optional cancellation token as a second argument. In the sample code below, I've included this argument. What I don't get is that if don't include the second argument, the code still works. Apparently, the action has access to the token even if it is not passed as an argument. So what's the purpose of passing it as an argument? Is there a situation in which the second argument would be needed or was it totally unnecessary for Microsoft to include this option?

var cts = new CancellationTokenSource();
var token = cts.Token;
Task.Factory.StartNew(() =>
{
    int i = 0;
    while (true)
    {
        token.ThrowIfCancellationRequested();
        Console.WriteLine($"{i++}\t");
        Thread.Sleep(500);
    }
}, token);
Console.ReadKey();
cts.Cancel();
FaizanHussainRabbani
  • 3,256
  • 3
  • 26
  • 46
Tim
  • 185
  • 1
  • 3
  • 15

3 Answers3

1

This is only useful in case the cancellation token gets cancelled before the tasks starts executing. If that happens, then the task won't be executed at all and will directly be marked as cancelled, saving some resources.

Kevin Gosse
  • 38,392
  • 3
  • 78
  • 94
1

For thread co-ordination in multi threaded environment simply. Second parameter is expecting CancellationToken which you can control from another thread as well (visualize this as like global variable) and can be used to cancel the task request.

One use case you might think of : you initiated two tasks fetching same data from two sources. Depending upon which task completes first, you might want to cancel another task still in progress. make sense ?

rahulaga-msft
  • 3,964
  • 6
  • 26
  • 44
0

Can't comment due to stackoverflow low points policy so writing here. This question is answered nicely in Why does TaskFactory.StartNew receive a CancellationToken which also happens to be a duplicate of another question.

  • 1
    Your code would work the same way without using the second argument of `Task.Factory.StartNew` – Kevin Gosse Feb 24 '18 at 11:37
  • Thanks @KevinGosse , I had misunderstood question and after initially deleting my old wrong answer I started research and got some resolution. Like mentioned in the answers of other questions, second Token argument is used for Task's status; so Task.Staus would not be cancel if Token not passed as a second argument. – Andrew Holer Feb 25 '18 at 06:17