Search code examples
task-parallel-library.net-4.5cancellationcancellation-token

What is the purpose of passing CancellationToken to Task.Factory.StartNew()


In the following code a CancellationToken is passed to the .StartNew(,) method as the 2nd parameter, but is only usable by the Action via the closure in the lambda. So, what is the purpose of passing the token through the .StartNew(,) method's 2nd parameter?

var cts = new CancellationTokenSource();
var token = cts.Token;
Task.Factory.StartNew(() => 
{
    while (true)
    {
        // simulate doing something useful
        Thread.Sleep(100);
    }
}, token);

Solution

  • StartNew method schedules a task in the tread pool, but not necessary start it right at the moment, because threads may be unavailable. During waiting for the start the cancellation request may occur, after which the thread pool wouldn't start a task at all. After task was started it's your job to handle cancellation of the task.