.net - 将 TaskContinuationOptions 应用于 "step"而不是整个链

标签 .net task-parallel-library

给定以下代码:

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

如果我按原样执行它 FirstAsyncMethod抛出异常,HandleErrors从未被调用,因为 TaskContinuationOptionsSecondAsyncMethod停止整个链。

另一方面,如果我删除了 TaskContinuationOptionsSecondAsyncMethod , 正在访问 Task.Result导致 AggregateException抛出 作为原始 AggregateException 的 InnerException。在我的实际代码中,这会产生一个需要解包的荒谬层次结构。

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

有没有办法申请TaskContinuationOptionsContinueWith以便它只可能跳过该步骤,而不会跳过任何后续步骤?

最佳答案

我通过将我的 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/

相关文章:

c# - 如何编辑Windows窗体资源文件夹中的文本文件#

.net - 带有 'If' 条件的 VB.NET 'Or' 语句是否双方都进行了评估?

c# - 将属性作为参数的通用函数

c# - Parallel.ForEach无法按预期的方式运行C#

c# - 通过DataGridView向集合添加元素

c# - 使用起订量需要帮助

股票行情指示器的 C# 异步任务

c# - 使用 Task.StartNew 方法时如何保证创建新线程

c# - 在任务中捕获异常的最佳方法是什么?

c# - 等待的奇怪行为