Get Task CancellationToken

前端 未结 4 1944
旧巷少年郎
旧巷少年郎 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: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).

提交回复
热议问题