Get Task CancellationToken

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

提交回复
热议问题