classic producer consumer pattern using blockingcollection and tasks .net 4 TPL

前端 未结 3 1844
醉酒成梦
醉酒成梦 2020-12-05 07:49

Please see below pseudo code

//Single or multiple Producers produce using below method
    void Produce(object itemToQueue)
    {
        concurrentQueue.enq         


        
3条回答
  •  误落风尘
    2020-12-05 08:38

    Your second block of code looks better. But, starting a Task and then immediately waiting on it is pointless. Just call Take and then process the item that is returned directly on the consuming thread. That is how the producer-consumer pattern is meant to be done. If you think the processing of work items is intensive enough to warrant more consumers then by all means start more consumers. BlockingCollection is safe multiple producers and multiple consumers.

    public class YourCode
    {
      private BlockingCollection queue = new BlockingCollection();
    
      public YourCode()
      {
        var thread = new Thread(StartConsuming);
        thread.IsBackground = true;
        thread.Start();
      }
    
      public void Produce(object item)
      {
        queue.Add(item);
      }
    
      private void StartConsuming()
      {
        while (true)
        {
          object item = queue.Take();
          // Add your code to process the item here.
          // Do not start another task or thread. 
        }
      }
    }
    
        

    提交回复
    热议问题