Processing only n items at a time concurrently using Task Parallel Library

前端 未结 3 658
醉话见心
醉话见心 2021-02-08 23:09

This is all happening in a windows service.

I have a Queue (actually a ConcurrentQueue) holding items waiting to be processed

3条回答
  •  既然无缘
    2021-02-08 23:38

    I'd also recommend using a BlockingCollection instead of directly using a ConcurrentQueue.

    Here's an example:

    public class QueuingRequestProcessor
    {
      private BlockingCollection queue;
    
      public void QueuingRequestProcessor(int maxConcurrent)
      {
        this.queue = new BlockingCollection(maxConcurrent);
    
        Task[] consumers = new Task[maxConcurrent];
    
        for (int i = 0; i < maxConcurrent; i++)
        {
          consumers[i] = Task.Factory.StartNew(() =>
          {
            // Will wait when queue is empty, until CompleteAdding() is called
            foreach (var request in this.queue.GetConsumingEnumerable())
            {
              Process(request);
            }
          });
        }
      }
    
      public void Add(MyRequest request)
      {
        this.queue.Add(request);
      }
    
      public void Stop()
      {
        this.queue.CompleteAdding();
      }
    
      private void Process(MyRequestType request)
      {
        // Do your processing here
      }
    }
    

    Note that maxConcurrent in the constructor defines how many requests will be processed concurrently.

提交回复
热议问题