title: Creating a non blocking async gate in C#
body: <p>I need to create a gate to a resource in an async programming model so that one and only one thread can have access to a resource at any given time. Given the async programming model I would like the remaining requests to the resource to be queued so that I don't blok threads while waiting for the resource to become available.</p>
  
  <p>I've looked and found a reader/writer gate in Jeffrey Richter's power threading library however I'm searching for something a bit different.</p>
  
  <p>I have a vague idea that I would like the signature of the gate class to look like this:</p>
  
  <pre><code>public class Gate
  {
    public IAsyncResult BeginEnterGate(AsyncCallback callback, object state)
    {
      ...
    }
  
    public GateRequest EndEnterGate(IAsyncResult result)
    {
      return ...;
    }
  }
  </code></pre>
  
  <p>The returned gate request should be IDisposable and when disposed the gate would allow the next thread to use the resource.</p>
  
  <pre><code>public class GateRequest : IDisposable
  {
    public void Dispose()
    {
      /* release gate */
    }
  }
  </code></pre>
  
  <p>By having this I can utilize Jefrey Ricters powerthreading libary like so:</p>
  
  <pre><code>public IAsyncResult BeginFoo(string bar, AsyncCallback callback, object state)
  {
    AsyncEnumerator ae = new AsyncEnumerator();
    return ae.BeginExecute(DoFoo(ae, bar), callback, state);
  }
  
  public void EndFoo(IAsyncResult result)
  {
    AsyncEnumerator.FromAsyncResult(result).EndExecute(result);
  }
  
  private IEnumerator&lt;int&gt; DoFoo(AsyncEnumerator ae, string bar)
  {
    gate.BeginEnterGate(ae.End(), null);
    yield return 1;
    var gateReleaser = gate.EndEnterGate(ae.DequeueAsyncResult());
  
    using (gateReleaser)
    {
      /* do work related to the resource */
    }
  }
  </code></pre>
  
  <p>I might be staring myself blind at a certain way to solve this, so I'm also open to other suggestions.</p>