C# Blocking Queue

If you’re writing a threaded application in C# and you need to wait until a resource becomes available, you can use this class. Very handy for producer/consumer scenarios.

public class BlockingQueue<T>
{
    Queue<T> que = new Queue<T>();
    Semaphore sem = new Semaphore(0, Int32.MaxValue);

    public void Enqueue(T item)
    {
        lock (que)
        {
            que.Enqueue(item);
        }

        sem.Release();
    }

    public T Dequeue()
    {
        sem.WaitOne();

        lock (que)
        {
            return que.Dequeue();
        }
    }
}