要确保在链接 MultipleActionBlock 时,BoundedCapacity 限制被尊重,需使用 ExecutionDataflowBlockOptions 对象来设置 BlockOption 类(BoundedCapacity 函数)。下面是可能的解决方案代码示例:
var options = new ExecutionDataflowBlockOptions
{
BoundedCapacity = 10 // 设置 BoundedCapacity 限制为 10
};
var blocks = new List>();
// 创建五个 ActionBlock 并将它们链接到 MultipleActionBlock 中
for (var i = 0; i < 5; i++)
{
var block = new ActionBlock(num => Console.WriteLine(num), options);
blocks.Add(block);
}
var multipleBlock = new JoinBlock(
blocks[0], blocks[1], blocks[2], blocks[3], blocks[4]);
// 将多输入 MultipleActionBlock 与输出链接
var outputBlock = new ActionBlock>(
tuple => Console.WriteLine($"{tuple.Item1} {tuple.Item2} {tuple.Item3} {tuple.Item4} {tuple.Item5}"), options);
multipleBlock.LinkTo(outputBlock, new DataflowLinkOptions { PropagateCompletion = true });
// 必须为多输入 MultipleActionBlock 启动所有 ActionBlock 才能开始处理数据
foreach (var block in blocks)
{
block.Post(1);
}
multipleBlock.Completion.Wait();
outputBlock.Complete();
outputBlock.Completion.Wait();
上面的代码创建了五个 ActionBlock,将它们链接到 MultipeActionBlock,并定义了 ExecutionDataflowBlockOptions 对象来设置 BoundedCapacity 限制。然后在输入数据之前启动所有 ActionBlock,并在完成后等待输出 Block 完成。