Get Task CancellationToken

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.


This seems to work:

public static CancellationToken GetCancellationToken(this Task task)
{
  return new TaskCanceledException(task).CancellationToken;
}

This can be necessary to make general-purpose Task helpers preserve the CancellationToken of a cancelled Task (I arrived here while trying to make Jon Skeet's WithAllExceptions method preserve the Token).


As other answers state, you can pass the token as a parameter to your method. However, it's important to remember that you still want to pass it to the Task as well. Task.Factory.StartNew( () => YourMethod(token), token), for example.

This insures that:

  1. The Task will not run if cancellation occurs before the Task executes (this is a nice optimization)

  2. An OperationCanceledException thrown by the called method correctly transitions the Task to a Canceled state


Can I get CancellationToken which was passed to Task constructor during task action executing?

No, you can't get it directly from the Task object, no.

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?

Those are two of the options, yes. There are others though. (Possibly not an inclusive list.)

  1. You can close over the cancellation token in an anonymous method

  2. You can pass it in as state

  3. You can ensure that the instance used for the task's delegate has an instance field that holds onto the cancellation token, or holds onto some object which holds onto the token, etc.

  4. You can expose the token though some other larger scope as state, i.e. as a public static field (bad practice in most cases, but it might occasionally be applicable)