Why use a cancel token for TaskFactory.StartNew?

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)); } }); } } ); //note that I removed the ", token" from here tokenSource.Cancel(); 

So, does something happen under this when I pass the cancel token to Task.Factory.StartNew?

thanks

+8
c # task-parallel-library
source share
1 answer

Two things will happen.

  • If the token was canceled before the StartNew call, it will never start the thread, and the task will be in the Canceled state.
  • If a OperationCanceledException raised from within the task, and this exception was thrown in the same token as StartNew , this will cause return The task to enter the Cancelled state. If the token associated with the exception is another token or you did not pass the token in the task, enter the Faulted state.

PS You should never call Task.Factory.StartNew without passing the TaskScheduler , because if you do not, it can easily make code run in the user interface thread that you expect to run in the background thread . Instead of Task.Run( use Task.Run( if you do not need to use StartNew , Task.Run has the same CancellationToken behavior as StartNew .

+7
source share

All Articles