首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用阻塞集合和任务的经典生产者-消费者模式.net 4第三方公共许可证

使用阻塞集合和任务的经典生产者-消费者模式.net 4第三方公共许可证
EN

Stack Overflow用户
提问于 2011-06-29 03:25:58
回答 2查看 27.1K关注 0票数 20

请看下面的伪代码

代码语言:javascript
复制
//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创建的任务和NET4的新信令特性的模式。换句话说,如果有人使用NET4编写这个模式,它会是什么样子?伪代码很好。正如你所见,我已经在使用.net 4 concurrentQueue了。我如何使用一个任务,如果可能的话,还可能使用一些新的信令机制。谢谢

感谢Jon/Dan,我的问题在下面得到了解决。甜。没有手动信令或while(true)或while(itemstoProcess)类型的循环

代码语言:javascript
复制
//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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6512033

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档