If your intention is to create a paired variant of the producer-consumer pattern then the sequence is Pulse
before Wait
for the producer and Wait
before Pulse
for the consumer. You can reference figure 5 in Joe Duffy's article on this. Howerver, keep in mind that since his implementation performs an unconditional Wait
in the Enqueue
method a ping-pong like effect will occur between the producer and the consumer. The queue, in his implementation, can only ever have one item per producer. So if that is your intention then this your ticket. Otherwise, you can adapt it as-is and apply some condition1 to the Wait
in the Enqueue
method to make it behave more like a real FIFO buffer.
However, like Reed, I question why BlockingCollection
could not be used. This collection should be very efficient since it uses a lock-free strategy for the Add
and Take
methods. Of course, like I mentioned above, if you really want the paired variant then this collection will not meet your requirements and you will have to roll your own using Joe Duffy's as a starting point.
1Just remember to use a while
loop instead of an if
check before applying the wait. Monitor.Wait
simply waits for a change in the lock state and nothing more so you have to recheck the wait condition.