gpt4 book ai didi

c# - 在 ActionBlock 中收集结果时阻止收集

转载 作者:行者123 更新时间:2023-11-30 15:16:52 24 4
gpt4 key购买 nike

我认为在测试方法中,“results”集合变量的类型必须是 BlockingCollection<int>而不是 List<int> .如果我错了,请证明给我看。我从 https://blog.stephencleary.com/2012/11/async-producerconsumer-queue-using.html 中获取了这个示例

private static async Task Produce(BufferBlock<int> queue, IEnumerable<int> values)
{
foreach (var value in values)
{
await queue.SendAsync(value);
}
}

public async Task ProduceAll(BufferBlock<int> queue)
{
var producer1 = Produce(queue, Enumerable.Range(0, 10));
var producer2 = Produce(queue, Enumerable.Range(10, 10));
var producer3 = Produce(queue, Enumerable.Range(20, 10));
await Task.WhenAll(producer1, producer2, producer3);
queue.Complete();
}

[TestMethod]
public async Task ConsumerReceivesCorrectValues()
{
var results = new List<int>();

// Define the mesh.
var queue = new BufferBlock<int>(new DataflowBlockOptions { BoundedCapacity = 5, });

//var consumerOptions = new ExecutionDataflowBlockOptions { BoundedCapacity = 1, };

var consumer = new ActionBlock<int>(x => results.Add(x), consumerOptions);
queue.LinkTo(consumer, new DataflowLinkOptions { PropagateCompletion = true, });

// Start the producers.
var producers = ProduceAll(queue);

// Wait for everything to complete.
await Task.WhenAll(producers, consumer.Completion);

// Ensure the consumer got what the producer sent.
Assert.IsTrue(results.OrderBy(x => x).SequenceEqual(Enumerable.Range(0, 30)));
}

最佳答案

ActionBlock<T>默认情况下将其委托(delegate)限制为一次执行一次( MaxDegreeOfParallelism1 ),没有必要使用 BlockingCollection<T>而不是 List<T> .

正如预期的那样,您代码中的测试对我来说顺利通过。

如果ActionBlock<T>通过了一个更高的选项 MaxDegreeOfParallelism , 那么你需要保护 List<T>或者用 BlockingCollection<T> 替换它.

关于c# - 在 ActionBlock 中收集结果时阻止收集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48337739/

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