title: awaitable Task based queue
body: <p>I'm wondering if there exists an implementation/wrapper for <a href="http://msdn.microsoft.com/en-us/library/dd267265.aspx" rel="noreferrer">ConcurrentQueue</a>, similar to <a href="http://msdn.microsoft.com/en-us/library/dd267312.aspx" rel="noreferrer">BlockingCollection</a> where taking from the collection does not block, but is instead asynchronous and will cause an async await until an item is placed in the queue.</p>
  
  <p>I've come up with my own implementation, but it does not seem to be performing as expected. I'm wondering if I'm reinventing something that already exists.</p>
  
  <p>Here's my implementation:</p>
  
  <pre><code>public class MessageQueue&lt;T&gt;
  {
      ConcurrentQueue&lt;T&gt; queue = new ConcurrentQueue&lt;T&gt;();
  
      ConcurrentQueue&lt;TaskCompletionSource&lt;T&gt;&gt; waitingQueue = 
          new ConcurrentQueue&lt;TaskCompletionSource&lt;T&gt;&gt;();
  
      object queueSyncLock = new object();
  
      public void Enqueue(T item)
      {
          queue.Enqueue(item);
          ProcessQueues();
      }
  
      public async Task&lt;T&gt; Dequeue()
      {
          TaskCompletionSource&lt;T&gt; tcs = new TaskCompletionSource&lt;T&gt;();
          waitingQueue.Enqueue(tcs);
          ProcessQueues();
          return tcs.Task.IsCompleted ? tcs.Task.Result : await tcs.Task;
      }
  
      private void ProcessQueues()
      {
          TaskCompletionSource&lt;T&gt; tcs=null;
          T firstItem=default(T);
          while (true)
          {
              bool ok;
              lock (queueSyncLock)
              {
                  ok = waitingQueue.TryPeek(out tcs) &amp;&amp; queue.TryPeek(out firstItem);
                  if (ok)
                  {
                      waitingQueue.TryDequeue(out tcs);
                      queue.TryDequeue(out firstItem);
                  }
              }
              if (!ok) break;
              tcs.SetResult(firstItem);
          }
      }
  }
  </code></pre>