3

给定以下代码:

// TCO = TaskContinuationOptions
FirstAsyncMethod()
    .ContinueWith(t => SecondAsyncMethod(t.Result), TCO.OnlyOnRanToCompletion)
    .ContinueWith(t => HandleErrors(t));

如果我按原样执行它并FirstAsyncMethod引发异常,HandleErrors则永远不会调用它,因为TaskContinuationOptionsonSecondAsyncMethod会停止整个链。

另一方面,如果我删除TaskContinuationOptionson SecondAsyncMethod,访问Task.Result会导致一个作为原始 AggregateException 的 InnerExceptionAggregateException被抛出。在我的实际代码中,这会产生一个需要展开的荒谬层次结构。

我没有捕获(即链) , 的结果ContinueWith,在这HandleErrors之前被调用,SecondAsyncMethod这显然是一个问题。

有没有办法应用TaskContinuationOptions到 aContinueWith以便它只可能跳过该步骤,而不是任何后续步骤?

4

1 回答 1

1

我通过将我的 HandleErrors 添加到链中的所有任务来解决这个问题,但使它们以父任务故障为条件。

Task task1 = new Task(FirstAsyncMethod());
Task task2 = task1.ContinueWith(t => SecondAsyncMethod(t.Result), TCO.OnlyOnRanToCompletion);


task1.ContinueWith(t => HandleErrors(t), TCO.OnlyOnFaulted);
task2.ContinueWith(t => HandleErrors(t), TCO.OnlyOnFaulted);
于 2013-01-17T03:53:58.910 回答