Get Task CancellationToken

前端 未结 4 1932
旧巷少年郎
旧巷少年郎 2021-02-12 04:24

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

Cancella         


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-12 05:10

    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)

提交回复
热议问题