gpt4 book ai didi

c# - 使用 blockingcollection 和 tasks 的经典生产者消费者模式 .net 4 TPL

转载 作者:IT王子 更新时间:2023-10-29 04:42:20 24 4
gpt4 key购买 nike

请看下面的伪代码

//Single or multiple Producers produce using below method
void Produce(object itemToQueue)
{
concurrentQueue.enqueue(itemToQueue);
consumerSignal.set;
}

//somewhere else we have started a consumer like this
//we have only one consumer
void StartConsumer()
{
while (!concurrentQueue.IsEmpty())
{
if (concurrentQueue.TrydeQueue(out item))
{
//long running processing of item
}
}
consumerSignal.WaitOne();
}

如何移植我自古以来就使用的这个模式,以使用 taskfactory 创建的任务和 net 4 的新信号功能。换句话说,如果有人使用 net 4 编写这个模式,它会是什么样子?伪代码很好。如您所见,我已经在使用 .net 4 concurrentQueue。我如何使用任务并可能使用一些更新的信号机制(如果可能)。谢谢

感谢 Jon/Dan 解决了我的问题。甜的。没有像过去那样的手动信号或 while(true) 或 while(itemstoProcess) 类型的循环

//Single or multiple Producers produce using below method
void Produce(object itemToQueue)
{
blockingCollection.add(item);
}

//somewhere else we have started a consumer like this
//this supports multiple consumers !
task(StartConsuming()).Start;

void StartConsuming()
{
foreach (object item in blockingCollection.GetConsumingEnumerable())
{
//long running processing of item
}
}

cancellations are handled using cancel tokens

最佳答案

您将使用 BlockingCollection<T> .文档中有一个示例。

该类是专门为使这变得微不足道而设计的。

关于c# - 使用 blockingcollection 和 tasks 的经典生产者消费者模式 .net 4 TPL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6512033/

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