gpt4 book ai didi

c# - TPL 数据流异步调度

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

async Task 的调度在 TPL 数据流中没有像我预期的那样工作。在下面的示例中,我希望 ActionBlockTransformBlock 可用时立即处理数据。但它正在等待第二个(延迟的)结果,然后再进行第三个。我在这里误解了什么?处理顺序有要求吗?

public class TestDataFlow
{
public System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();

public async Task Flow()
{
watch.Start();

var plus10 = new TransformBlock<int, int>(async input =>
{
if (input == 2)
{
await Task.Delay(5000);
}
Console.WriteLine("Exiting plus10 for input {0} @ {1}", input, watch.Elapsed);
return input + 10;
},
new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = 4,
});

var printSolution = new ActionBlock<int>(input =>
{
Console.WriteLine("Solution: {0} @ {1}", input, watch.Elapsed.TotalMilliSeconds);
},
new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = 4,
});

plus10.LinkTo(printSolution);

List<int> inputs = new List<int> { 1, 2, 3 };
foreach (var input in inputs)
{
await plus10.SendAsync(input);
}
}
}

输出:

Exiting plus10 for input 1 @ 115.8583
Exiting plus10 for input 3 @ 116.6973
Solution: 11 @ 126.0146
Exiting plus10 for input 2 @ 5124.4074
Solution: 12 @ 5124.9014
Solution: 13 @ 5126.4834

最佳答案

无论并行处理多少项目,TPL Dataflow 都能保证输入和输出队列的顺序。

"Because each predefined source dataflow block type guarantees that messages are propagated out in the order in which they are received, every message must be read from the source block before the source block can process the next message"

来自 Dataflow (Task Parallel Library)

如果您希望项目在完成处理时准确地移动到下一个 block ,您应该自己明确地传输它们,这会将您的 TransformBlock 转换为 ActionBlock:

var printSolution = new ActionBlock<int>(input =>
{
Console.WriteLine("Solution: {0} @ {1}", input, watch.Elapsed.TotalMilliSeconds);
},executionDataflowBlockOptions);

var plus10 = new ActionBlock<int>(async input =>
{
if (input == 2)
{
await Task.Delay(5000);
}
Console.WriteLine("Exiting plus10 for input {0} @ {1}", input, watch.Elapsed);
await printSolution.SendAsync(input + 10);
}, executionDataflowBlockOptions);

关于c# - TPL 数据流异步调度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27170913/

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