Creating a blocking Queue in .NET?

后端 未结 10 830
半阙折子戏
半阙折子戏 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:31

    I just knocked this up using the Reactive Extensions and remembered this question:

    public class BlockingQueue
    {
        private readonly Subject _queue;
        private readonly IEnumerator _enumerator;
        private readonly object _sync = new object();
    
        public BlockingQueue()
        {
            _queue = new Subject();
            _enumerator = _queue.GetEnumerator();
        }
    
        public void Enqueue(T item)
        {
            lock (_sync)
            {
                _queue.OnNext(item);
            }
        }
    
        public T Dequeue()
        {
            _enumerator.MoveNext();
            return _enumerator.Current;
        }
    }
    

    Not necessarily entirely safe, but very simple.

提交回复
热议问题