gpt4 book ai didi

c# - 具有 BoundedCapacity 的 BufferBlock 和 ActionBlock 不使用最大 DOP

转载 作者:太空狗 更新时间:2023-10-29 22:58:38 24 4
gpt4 key购买 nike

我有这个代码:

var data = new BufferBlock<int>(new DataflowBlockOptions { BoundedCapacity = 1 });

var action = new ActionBlock<int>(async id =>
{
Console.WriteLine("[{0:T}] #{1}: Start", DateTime.Now, id);

await Task.Delay(1000);

Console.WriteLine("[{0:T}] #{1}: End", DateTime.Now, id);
}, new ExecutionDataflowBlockOptions
{
BoundedCapacity = 1,
MaxDegreeOfParallelism = -1
});

data.LinkTo(action, new DataflowLinkOptions { PropagateCompletion = true });

for (var id = 1; id <= 3; id++)
{
Console.WriteLine("[{0:T}] Sending {1}", DateTime.Now, id);
data.SendAsync(id).Wait();
Console.WriteLine("[{0:T}] Sending {1} complete", DateTime.Now, id);
}

data.Complete();

Task.WhenAll(data.Completion, action.Completion).Wait();

这段代码得到了这个输出:

[22:31:22] Sending 1
[22:31:22] Sending 1 complete
[22:31:22] Sending 2
[22:31:22] #1: Start
[22:31:22] Sending 2 complete
[22:31:22] Sending 3
[22:31:23] #1: End
[22:31:23] #2: Start
[22:31:23] Sending 3 complete
[22:31:24] #2: End
[22:31:24] #3: Start
[22:31:25] #3: End

为什么 ActionBlock 没有并行工作,即使它有一个无限的 DOP?

最佳答案

ActionBlock 似乎具有有限并行度的原因是因为它的 BoundedCapacity 为 1。BoundedCapacity(与 InputCount) 包括当前正在处理的项目。这可以很容易地证明:

var block = new ActionBlock<int>(_ => Task.Delay(-1), new ExecutionDataflowBlockOptions
{
BoundedCapacity = 1,
MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded
});

await block.SendAsync(4); // Adds a new item
await block.SendAsync(4); // Blocks forever

这意味着当您设置 MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded 时,该 block 当时不能接受超过一个项目,因此实际上限制了您的并行度。

您可以通过设置更大的 BoundedCapacity 来解决这个问题:

var action = new ActionBlock<int>(async id =>
{
Console.WriteLine("[{0:T}] #{1}: Start", DateTime.Now, id);
await Task.Delay(1000);
Console.WriteLine("[{0:T}] #{1}: End", DateTime.Now, id);
}, new ExecutionDataflowBlockOptions
{
BoundedCapacity = 10,
MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded
});

关于c# - 具有 BoundedCapacity 的 BufferBlock 和 ActionBlock 不使用最大 DOP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26577051/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com