【发布时间】:2023-03-19 12:53:02
【问题描述】:
我有这个代码:
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?
【问题讨论】:
标签: c# .net task-parallel-library async-await tpl-dataflow