【发布时间】:2018-02-16 15:59:01
【问题描述】:
我有以下伪代码:
var queue = new BufferBlock<int>(new DataflowBlockOptions { BoundedCapacity = 5 });
var a = new ActionBlock<int>(async item =>
{
await Task.Delay(500);
Trace.TraceInformation(
$"Target 1: | Type: {typeof(int).Name} | Thread: {Thread.CurrentThread.ManagedThreadId} | Message: {item}");
// handling some logic but it throws
if (item >= 5) throw new Exception("Something bad happened");
}, new ExecutionDataflowBlockOptions { BoundedCapacity = 1, MaxDegreeOfParallelism = 1 });
queue.LinkTo(a, new DataflowLinkOptions { PropagateCompletion = true });
var targets = new List<ITargetBlock<int>> {queue};
var broadcaster = new ActionBlock<int>(
async item =>
{
var processingTasks = targets.Select(async t =>
{
try
{
// This is condition is always false
// t (bufferblock) has no exceptions. Exception is raised in downstream action block where it sends to
if (!await t.SendAsync(item))
await t.Completion;
}
catch (Exception e)
{
Trace.TraceInformation("Handled exception : " + e.Message);
}
});
try
{
// Neither here the exception is rethrowed
await Task.WhenAll(processingTasks);
}
catch (Exception e)
{
Trace.TraceInformation("Handled exception WhenAll : " + e.Message);
}
});
for (var i = 1; i <= 10; i++)
{
broadcaster.Post(i);
}
管道是这样配置的ActionBlock<int> => BufferBlock<int> => ActionBlock<int>。
最后一个ActionBlock<int> 抛出异常,但它不会重新抛出到我想处理它的源代码块。
如何重写这段代码以正确处理异常?
【问题讨论】:
-
您无法处理来自其他块的异常。当您
Post或SendAsync向 tpl 块发送消息时,它只会将其添加到它的缓冲区中,仅此而已,您对它也没有任何参考,也不会引发异常。 -
如果 ˋt` 是引发异常的另一个动作块,它确实有效。我的问题更多是关于如何设计具有良好异常处理能力的管道,而不是在许多地方传播尝试捕获
标签: c# exception-handling task-parallel-library tpl-dataflow