问题描述
请参见下面的伪代码
//单个或多个生产者产生使用下面的方法
无效农产品(对象itemToQueue)
{
concurrentQueue.enqueue(itemToQueue);
consumerSignal.set;
}
//别的地方我们已经开始这样
消费者//我们只有一个消费
无效StartConsumer()
{
而(!concurrentQueue.IsEmpty())
{
如果(concurrentQueue.TrydeQueue(出项))
{
//长时间运行的项目
的处理}
}
consumerSignal.WaitOne();
}
我如何端口这种模式,因为那时我已经使用自古以来使用taskfactory创建任务和净4.新的信令功能,换句话说,如果有人写使用net 4怎么是这样的格局?伪代码是罚款。 IAM已经在使用.NET 4 concurrentQueue,你可以看到。如何使用一个任务,如果可能的话可能用一些较新的信号机制。谢谢
解决我的问题感谢乔恩/丹下方。甜。
无人工信令或同时(真)或同时(itemstoProcess)型像旧天环
//单或多个生产者产生使用下面的方法
无效农产品(对象itemToQueue)
{
blockingCollection.add(项目);
}
//别的地方我们已经开始这样
消费者//这个支持多消费者!
任务(StartConsuming())启动。
无效StartConsuming()项$ B的
{
的foreach
{
(在blockingCollection.GetConsumingEnumerable()对象项目)//长时间运行的处理$ b}
}
取消使用取消令牌
处理
您将使用。还有的文档中的例子。
这类专门设计,使这个微不足道的。
Please see below pseudo code
//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();
}
How do I port this pattern I have used since time immemorial to use taskfactory created tasks and the new signalling features of net 4. In other words if someone were to write this pattern using net 4 how would it look like ? Pseudo code is fine. Iam already using .net 4 concurrentQueue as you can see. How do I use a task and possibly use some newer signalling mechanism if possible. thanks
Solution to my problem below thanks to Jon/Dan. Sweet.No manual signalling or while(true) or while(itemstoProcess) type loops like the old days
//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
You would use BlockingCollection<T>
. There's an example in the documentation.
That class is specifically designed to make this trivial.
这篇关于使用blockingcollection和任务.NET 4 TPL经典生产者消费者模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!