Why pass cancellation token to TaskFactory.StartNew?

Viewed 2217

Besides the most common form of calling TaskFactory.StartNew with only the "action" parameter (1) https://msdn.microsoft.com/en-us/library/dd321439(v=vs.110).aspx

we alse have one method that accepts an extra parameter as the "Cancelation Token" (2) https://msdn.microsoft.com/en-us/library/dd988458.aspx

My question is, why should we use the call (2) instead of call (1)?

I mean, the example in MSDN for page (2) would also work if I don't pass the Cancellation Token as parameter (because the variable token is accessible from the delegate function. Something like:

var tokenSource = new CancellationTokenSource();
      var token = tokenSource.Token;
      var files = new List<Tuple<string, string, long, DateTime>>();

      var t = Task.Factory.StartNew( () => { string dir = "C:\\Windows\\System32\\";
                                object obj = new Object();
                                if (Directory.Exists(dir)) {
                                   Parallel.ForEach(Directory.GetFiles(dir),
                                   f => {
                                           if (token.IsCancellationRequested)
                                              token.ThrowIfCancellationRequested();
                                           var fi = new FileInfo(f);
                                           lock(obj) {
                                              files.Add(Tuple.Create(fi.Name, fi.DirectoryName, fi.Length, fi.LastWriteTimeUtc));          
                                           }
                                      });
                                 }
                              }
                        ); //note that I removed the ", token" from here
      tokenSource.Cancel();

So is there anything happening underneath when I pass cancellation token to Task.Factory.StartNew?

Thanks

1 Answers
Related