title: Concurrent collection for .NET with timeouts?
body: <p>I have a concurrent collection.</p>
  
  <pre><code>var q = new ConcurrentQueue&lt;int&gt;(); // Or a stack/bag/etc...
  </code></pre>
  
  <p>I can get an item like this.</p>
  
  <pre><code>int i;
  if (q.TryDequeue(out i))
      DoStuff(i);
  </code></pre>
  
  <p>But I need it like "wait 10 seconds before returning false in case someone adds a new item":</p>
  
  <pre><code>int i;
  if (q.TryDequeue(TimeSpan.FromSeconds(10), out i))
      DoStuff(i);
  </code></pre>
  
  <p>I could write an extension method like this:</p>
  
  <pre><code>public static bool TryDequeue&lt;T&gt;(
      this ConcurrentQueue&lt;T&gt; queue,
      TimeSpan timeout,
      out T result)
  {
      // Validations...
  
      for (int i = 0; i &lt; 2; i++)
      {
          if (queue.TryDequeue(out result))
              return true;
          else if (i == 1)
              return false;
  
          Thread.Sleep(timeout);
      }
  }
  </code></pre>
  
  <p>But what if someone adds an item to the queue in 5 seconds, I don't want to wait 5 more.</p>
  
  <p>Is there any thread-safe collection that supports this feature in .NET?</p>