Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 747
Sean B Avatar asked Nov 09 '16 22:11

Sean B


People also ask

What does task factory StartNew do?

StartNew(Action<Object>, Object, CancellationToken, TaskCreationOptions, TaskScheduler) Creates and starts a task for the specified action delegate, state, cancellation token, creation options and task scheduler.

What is the purpose of CancellationToken?

A CancellationToken enables cooperative cancellation between threads, thread pool work items, or Task objects. You create a cancellation token by instantiating a CancellationTokenSource object, which manages cancellation tokens retrieved from its CancellationTokenSource. Token property.

What is CancellationToken C# task?

The CancellationToken is used in asynchronous task. The CancellationTokenSource token is used to signal that the Task should cancel itself. In the above case, the operation will just end when cancellation is requested via Cancel() method.

What is difference between CancellationTokenSource and CancellationToken?

A CancellationTokenSource object, which provides a cancellation token through its Token property and sends a cancellation message by calling its Cancel or CancelAfter method. A CancellationToken object, which indicates whether cancellation is requested.


1 Answers

Actually, the purpose of the CancellationToken passed to Task.Run and Taskfactory.StartNew is to allow the task to differentiate being cancelled by an exception thrown from CancellationToken.ThrowIfCancellationRequested and failing because of any other exception.

That is, if the CancellationToken passed at start throws, the task's state is Cancelled while any other exception (even from another CancellationToken) will set it to Faulted.

Also, if the CancellationToken is cancelled before the task actually starts, it won't be started at all.

like image 76
Haukinger Avatar answered Sep 27 '22 23:09

Haukinger