Get Task CancellationToken

SiberianGuy picture SiberianGuy · Mar 15, 2013 · Viewed 12.6k times · Source

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?

Answer

Reed Copsey picture Reed Copsey · Mar 15, 2013

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.