Task Cancelled Exception (ThrowForNonSuccess)

前端 未结 1 1555
走了就别回头了
走了就别回头了 2021-02-08 11:41

This is a continuation from this question: Multiple Task Continuation

I have changed my code as in the answer, however now I am receiving TaskCancelledExceptions

相关标签:
1条回答
  • 2021-02-08 12:11

    You say that SetCancelledHandler just adds a continuation to the task. I assume that's the same task RunAsync gets as a parameter although i can't tell by your code how SetCancelledHandler gets a task to continue on (I assume we're missing some code). Anyways...

    You register 3 continuations on a task that will run when the task completes, is canceled and is faulted. Now let's assume the original task ran to completion successfully without being canceled. That means that 2 of your continuations (OnCanceled and OnFaulted) will not run because they don't need to be. The way to tell a task to not run in the TPL is to cancel it, and that happens automatically.

    The difference between your 2 code snippets is that in the first one you await the task continuations, and they get canceled which explains your exception. On the second snippet you don't await the continuations, just the original task that successfully ran to completion.

    P.S: I think the second option is more appropriate. You don't need to await all those continuations. You want to let them run if they need to.

    TL;DR: You await a canceled continuation task. The continuation task, not the original, is the one that throws an exception.

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