Monitor.Wait, Condition variable

Viewed 6351

Given a following code snippet(found in somewhere while learning threading).

 public class BlockingQueue<T>
    {
        private readonly object sync = new object();
        private readonly Queue<T> queue;
        public BlockingQueue()
        {
            queue = new Queue<T>();
        }

        public void Enqueue(T item)
        {
            lock (sync)
            {
                queue.Enqueue(item);
                Monitor.PulseAll(sync);
            }

        }
        public T Dequeue()
        {
            lock (sync)
            {
                while (queue.Count == 0)
                    Monitor.Wait(sync);

                return queue.Dequeue();
            }

        }
    }

What I want to understand is ,

Why is there a while loop ?

   while (queue.Count == 0)
            Monitor.Wait(sync);

and what is wrong with the,

 if(queue.Count == 0)
       Monitor.Wait(sync);

In fact, all the time when I see the similar code I found using while loop, can anyone please help me understand the use of one above another. Thank you.

5 Answers
Related