请看以下伪代码。
以下是Jon/Dan提供的解决方案。不用手动信号,也不需要while(true)或while(itemstoProcess)类型的循环,简单易懂。
//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