Can I get CancellationToken
which was passed to Task
constructor during task action executing. Most of samples look like this:
Cancella
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.)
You can close over the cancellation token in an anonymous method
You can pass it in as state
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.
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)