title: Dequeue from a ConcurrentQueue only if a condition is met
body: <p>How can I dequeue the next element of a <code>ConcurrentQueue</code> only if some condition is met?</p>
  
  <p>E.g. if the next item to be dequeued fullfills a certain condition, dequeue it, otherwise leave it. Essentially a <code>'DequeueIf'</code> or <code>'TryDequeueIf'</code> method</p>
  
  <p>Example:</p>
  
  <pre><code>var myQueue = new ConcurrentQueue&lt;int&gt;()
  ...
  int item;
  // only dequeue if the next item is 0
  bool success = myQueue.TryDequeueIf(out item, x=&gt;x==0) 
  </code></pre>
  
  <p>It is of course possible to first call <code>TryPeek</code>, check the condition, and then <code>TryDequeue</code>, but that is no longer threadsafe.</p>
  
  <p>I can wrap the whole <code>TryPeek &amp; TryDequeue</code> in a lock, but that kinda defeats the purpose of using ConcurrentQueue; and means that all regular unconditional dequeues will also have to be locked. I am not sure whether I would even have to lock over every <code>Enqueue</code> to be save. If possible, I would like to avoid the possible pitfals of implementing my own lock-strategy.</p>
  
  <p>Is there a lock-free solution using the .net4.0 <code>ConcurrentQueue</code> class or one of the other concurrent classes?</p>