Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Task CancellationToken

Can I get CancellationToken which was passed to Task constructor during task action executing. Most of samples look like this:

CancellationTokenSource cts = new CancellationTokenSource(); CancellationToken token = cts.Token;  Task myTask = Task.Factory.StartNew(() => {     for (...)     {         token.ThrowIfCancellationRequested();          // Body of for loop.     } }, token); 

But what if my action is not lambda but a method placed in other class and I don't have direct access to token? Is the only way is to pass token as state?

like image 765
SiberianGuy Avatar asked Mar 15 '13 18:03

SiberianGuy


People also ask

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?

CancellationTokenSource – an object responsible for creating a cancellation token and sending a cancellation request to all copies of that token. CancellationToken – a structure used by listeners to monitor token current state.

Can I reuse CancellationTokenSource?

CancellationTokenSource is quite a heavyweight object and its not normally cancelled; however it can't be pooled or reused because its registrations cannot be cleared.

How can I check my cancellation token?

The wait handle of the cancellation token will become signaled in response to a cancellation request, and the method can use the return value of the WaitAny method to determine whether it was the cancellation token that signaled. The operation can then just exit, or throw an OperationCanceledException, as appropriate.


1 Answers

But what if my action is not lambda but a method placed in other class and I don't have direct access to token? Is the only way is to pass token as state?

Yes, in that case, you would need to pass the token boxed as state, or included in some other type you use as state.

This is only required if you plan to use the CancellationToken within the method, however. For example, if you need to call token.ThrowIfCancellationRequested().

If you're only using the token to prevent the method from being scheduled, then it's not required.

like image 64
Reed Copsey Avatar answered Sep 18 '22 18:09

Reed Copsey