Creating a blocking Queue in .NET?

后端 未结 10 827
半阙折子戏
半阙折子戏 2020-11-22 01:14

I have a scenario where I have multiple threads adding to a queue and multiple threads reading from the same queue. If the queue reaches a specific size all threads<

相关标签:
10条回答
  • 2020-11-22 01:39

    If you want maximum throughput, allowing multiple readers to read and only one writer to write, BCL has something called ReaderWriterLockSlim that should help slim down your code...

    0 讨论(0)
  • 2020-11-22 01:41

    Starting with .NET 5.0/Core 3.0 you can use System.Threading.Channels
    Benchmarks from this (Asynchronous Producer Consumer Pattern in .NET (C#)) article show a significant speed boost over BlockingCollection!

    0 讨论(0)
  • 2020-11-22 01:43

    I haven't fully explored the TPL but they might have something that fits your needs, or at the very least, some Reflector fodder to snag some inspiration from.

    Hope that helps.

    0 讨论(0)
  • 2020-11-22 01:51

    You can use the BlockingCollection and ConcurrentQueue in the System.Collections.Concurrent Namespace

     public class ProducerConsumerQueue<T> : BlockingCollection<T>
    {
        /// <summary>
        /// Initializes a new instance of the ProducerConsumerQueue, Use Add and TryAdd for Enqueue and TryEnqueue and Take and TryTake for Dequeue and TryDequeue functionality
        /// </summary>
        public ProducerConsumerQueue()  
            : base(new ConcurrentQueue<T>())
        {
        }
    
      /// <summary>
      /// Initializes a new instance of the ProducerConsumerQueue, Use Add and TryAdd for Enqueue and TryEnqueue and Take and TryTake for Dequeue and TryDequeue functionality
      /// </summary>
      /// <param name="maxSize"></param>
        public ProducerConsumerQueue(int maxSize)
            : base(new ConcurrentQueue<T>(), maxSize)
        {
        }
    
    
    
    }
    
    0 讨论(0)
提交回复
热议问题