Get Task CancellationToken

前端 未结 3 1831
攒了一身酷
攒了一身酷 2021-02-12 04:22

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

Cancella         


        
3条回答
  •  旧时难觅i
    2021-02-12 04:56

    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

提交回复
热议问题