Advertisement
L_B

BlockingQueue

L_B
Feb 18th, 2012
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.40 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4.  
  5. namespace MyCollections
  6. {
  7.     public class BlockingQueue<T> : IDisposable
  8.     {
  9.         Queue<T> _Queue = new Queue<T>();
  10.         SemaphoreSlim _ItemsInQueue = null;
  11.         SemaphoreSlim _FreeSlots = null;
  12.         int _MaxItems = -1;
  13.  
  14.         public BlockingQueue(int maxItems = Int32.MaxValue)
  15.         {
  16.             _MaxItems = maxItems;
  17.             _ItemsInQueue = new SemaphoreSlim(0, maxItems);
  18.             _FreeSlots = new SemaphoreSlim(maxItems, maxItems);
  19.         }
  20.  
  21.         public void Dispose()
  22.         {
  23.             if (_ItemsInQueue != null) _ItemsInQueue.Dispose();
  24.             if (_FreeSlots != null) _FreeSlots.Dispose();
  25.         }
  26.  
  27.         public int Count
  28.         {
  29.             get { return _ItemsInQueue.CurrentCount; }
  30.         }
  31.  
  32.  
  33.         public void Add(T item)
  34.         {
  35.             if (_MaxItems != Int32.MaxValue) _FreeSlots.Wait();
  36.             lock (this)
  37.             {
  38.                 _Queue.Enqueue(item);
  39.                 _ItemsInQueue.Release();
  40.             }
  41.         }
  42.  
  43.  
  44.         public T Take()
  45.         {
  46.             T item = default(T);
  47.             _ItemsInQueue.Wait();
  48.             lock (this)
  49.             {
  50.                 item = _Queue.Dequeue();
  51.                 if (_MaxItems != Int32.MaxValue) _FreeSlots.Release();
  52.             }
  53.             return item;
  54.         }
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement