给定以下代码:
// TCO = TaskContinuationOptions
FirstAsyncMethod()
.ContinueWith(t => SecondAsyncMethod(t.Result), TCO.OnlyOnRanToCompletion)
.ContinueWith(t => HandleErrors(t));
如果我按原样执行它 FirstAsyncMethod
抛出异常,HandleErrors
从未被调用,因为 TaskContinuationOptions
在 SecondAsyncMethod
停止整个链。
另一方面,如果我删除了 TaskContinuationOptions
在 SecondAsyncMethod
, 正在访问 Task.Result
导致 AggregateException
抛出 作为原始 AggregateException 的 InnerException。在我的实际代码中,这会产生一个需要解包的荒谬层次结构。
我没有捕获(即链接)ContinueWith
的结果, HandleErrors
在 SecondAsyncMethod
之前被调用这显然是一个问题。
有没有办法申请TaskContinuationOptions
到 ContinueWith
以便它只可能跳过该步骤,而不会跳过任何后续步骤?
最佳答案
我通过将我的 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);
关于.net - 将 TaskContinuationOptions 应用于 "step"而不是整个链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14371166/