我有以下伪代码:
管道被配置为这样
最后一个
如何重写此代码以正确处理异常?
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
消息时,它只会将其添加到缓冲区中,这就是全部,你既没有对它的引用,也没有对抛出的异常的引用。 - VMAtmt
是另一个引发异常的操作块,它确实可以工作。我的问题更多地涉及如何设计具有良好异常处理的管道,而不是在许多地方散布try catch。 - Tomasz Jaskuλa