In addition to the most common form of calling TaskFactory.StartNew with the "action" parameter (1) https://msdn.microsoft.com/en-us/library/dd321439(v=vs.110).aspx
We have one method that accepts an additional parameter as the "Token Current", (2) https://msdn.microsoft.com/en-us/library/dd988458.aspx
My question is: why should we use call (2) instead of call (1)?
I mean, the example in MSDN for page (2) will also work if I don't pass the cancel token as a parameter (since 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)); } }); } } );
So, does something happen under this when I pass the cancel token to Task.Factory.StartNew?
thanks
c # task-parallel-library
Zรฉ Carlos
source share