title: An asynchronous counter which can be awaited on
body: <p>I have a connection class which has several async methods such as SendText, SendImage etc.</p>
  
  <p>The connection class has a Disconnect method, and when it is called I have to be careful not to start changing the inner state of the class before all async methods have completed execution.</p>
  
  <p>I believe a good way to achieve this is to simply keep a running total of the number of operations in execution, and then when I want to Disconnect I can simply set Disconnecting = true and then wait for the count to reach 0</p>
  
  <p>I'm thinking of something along the lines of this</p>
  
  <pre><code>class ReferenceCounter
  {
      void Increment();
  
      void Decrement();
  
      async Task WaitForCounterToReachZero();
  }
  </code></pre>
  
  <p>Then when an async operation starts I could do</p>
  
  <pre><code>refCounter.Increment();
  </code></pre>
  
  <p>When it ends</p>
  
  <pre><code>refCounter.Decrement();
  </code></pre>
  
  <p>and inside the Disconnect method</p>
  
  <pre><code>disconnecting = true;
  taskCancellationSource.Cancel();
  await refCounter.WaitForCounterToReachZero();
  Cleanup();
  </code></pre>
  
  <p>Are there any built in .NET classes like this?</p>
  
  <p>Or more importantly for me, is there a better way of doing this?</p>
  
  <p>If it was synchronous code it would be as simple as</p>
  
  <pre><code>lock (thisLock)
  {
      while (counter &gt; 0)
          Monitor.Wait(thisLock);
  }
  </code></pre>
  
  <p>I just found the built in CountdownEvent class which does the same thing, but it has no async Wait method nor does it have any events, so I'd have to block.</p>