【发布时间】:2011-09-24 14:49:36
【问题描述】:
请看下面的伪代码
//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
【问题讨论】:
-
一个非常好的(因为它是一步一步的)解释和例子may be found here。
-
嗨 Gullu,请查看this code。这是一个关于如何将 BlockingCollection
用于生产者-消费者模式的简单工作示例。
标签: c# multithreading scheduled-tasks task-parallel-library pfx