title: How to dispose asynchronously?
body: <p>Let's say I have a class that implements the <strong>IDisposable</strong> interface. Something like this:</p>
  
  <p><img src="https://farm4.static.flickr.com/3199/3149605015_f090f20185_o.png" alt="http://www.flickr.com/photos/garthof/3149605015/"></p>
  
  <p><strong>MyClass</strong> uses some unmanaged resources, hence the <em>Dispose()</em> method from <strong>IDisposable</strong> releases those resources. <strong>MyClass</strong> should be used like this:</p>
  
  <pre><code>using ( MyClass myClass = new MyClass() ) {
      myClass.DoSomething();
  }
  </code></pre>
  
  <hr>
  
  <p>Now, I want to implement a method that calls <em>DoSomething()</em> asynchronously. I add a new method to <strong>MyClass</strong>:</p>
  
  <p><img src="https://farm4.static.flickr.com/3103/3149605005_bde86e4e0b_o.png" alt="http://www.flickr.com/photos/garthof/3149605005/"></p>
  
  <p>Now, from the client side, <strong>MyClass</strong> should be used like this:</p>
  
  <pre><code>using ( MyClass myClass = new MyClass() ) {
      myClass.AsyncDoSomething();
  }
  </code></pre>
  
  <p>However, if I don't do anything else, this could fail as the object <em>myClass</em> might be disposed before <em>DoSomething()</em> is called (and throw an unexpected <strong>ObjectDisposedException</strong>). So, the call to the <em>Dispose()</em> method (either implicit or explicit) should be delayed until the asynchronous call to <em>DoSomething()</em> is done. </p>
  
  <p>I think the code in the <em>Dispose()</em> method should be executed <strong>in a asynchronous way, and only once all asynchronous calls are resolved</strong>. I'd like to know which could be the best way to accomplish this.</p>
  
  <p>Thanks.</p>
  
  <p><em>NOTE: For the sake of simplicity, I haven't entered in the details of how Dispose() method is implemented. In real life I usually follow the <a href="http://msdn.microsoft.com/en-us/library/fs2xkftw(VS.80).aspx" rel="noreferrer">Dispose pattern</a>.</em></p>
  
  <hr>
  
  <p><strong>UPDATE:</strong> Thank you so much for your responses. I appreciate your effort. As <a href="https://stackoverflow.com/users/3055/chakrit">chakrit</a> <a href="https://stackoverflow.com/questions/400130/how-to-dispose-asynchronously#400165">has commented</a>, I need that <strong>multiple calls to the async DoSomething can be made</strong>. Ideally, something like this should work fine:</p>
  
  <pre><code>using ( MyClass myClass = new MyClass() ) {
  
      myClass.AsyncDoSomething();
      myClass.AsyncDoSomething();
  
  }
  </code></pre>
  
  <p>I'll study the counting semaphore, it seems what I'm looking for. It could also be a design problem. If I find it convenient, I will share with you some bits of the real case and what <strong>MyClass</strong> really does.</p>