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);
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With