This project has moved. For the latest updates, please go here.


This is an advanced type that is only useful if you're creating your own async-ready coordination primitives.

An AsyncWaitQueue maintains a queue of TaskCompletionSource instances. It is not thread-safe and assumes that it is called back while under lock (a standard .NET lock, not an AsyncLock or logical lock). The AsyncAwaitQueue is a cancel-safe queue, guaranteeing that a TaskCompletionSource entry will either be retrieved from the queue or be canceled, but never both. In other words, tasks returned from TryDequeue are always completed, never canceled.

To add a Task to an AsyncWaitQueue, call Enqueue and pass it the object you lock to synchronize access to that wait queue, along with an optional CancellationToken that will cancel the wait. Enqueue will attach logic to the CancellationToken that will acquire the lock object, remove the task from the wait queue, and cancel it. Optionally, you can also pass the default result of the task, which will be used to complete the task unless a different result is passed into the dequeue method.

To complete a single waiting Task, call TryDequeue. To complete all waiting tasks, call DequeueAll. Both TryDequeue and DequeueAll take an optional result that is used to complete the task. If you need to cancel a Task directly (i.e., not through its CancellationToken), you can call TryCancel. Most async-ready coordination primitives do not need to call TryCancel.


// A queue of cancelable TaskCompletionSource<T> instances.
// This class is NOT threadsafe.
// All task continuations are executed in the background, since this class assumes it is always under lock.
public sealed class AsyncWaitQueue<T>
  // Creates a new wait queue.
  public AsyncWaitQueue();

  // Gets the number of tasks waiting in this queue.
  public int Count { get; }

  // Creates a new entry and queues it to this wait queue.
  public Task<T> Enqueue(object syncObject, CancellationToken token);
  public Task<T> Enqueue(object syncObject, CancellationToken token, T defaultResult);

  // Attempts to complete and remove a single entry in the wait queue.
  // If the wait queue is empty, this method returns null.
  public Task<T> TryDequeue();
  public Task<T> TryDequeue(T result);

  // Completes and removes all entries in the wait queue.
  public void DequeueAll();
  public void DequeueAll(T result);

  // Attempts to cancel and remove an entry from the wait queue.
  public bool TryCancel(Task task);

Last edited Nov 24, 2012 at 3:39 AM by StephenCleary, version 2


No comments yet.