Get Task CancellationToken

前端 未结 4 1945
旧巷少年郎
旧巷少年郎 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 04:54

    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

    0 讨论(0)
  • 2021-02-12 04:59

    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).

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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)

    0 讨论(0)
提交回复
热议问题