Get Task CancellationToken

前端 未结 4 1934
旧巷少年郎
旧巷少年郎 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:02

    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.

提交回复
热议问题