title: Using Await Async WhenAll with Disposable Objects
body: <p>I've hit a problem trying to process multiple Tasks in parallel (or however the runtime feels fit) when using disposable objects. In the following code snippet, each Processor object is immediately disposed BEFORE it has done the required work.</p>
  
  <pre><code>async public Task ProcessData(IEnumerable&lt;int&gt; data)
  {
      var tasks = new List&lt;Task&gt;();
  
      foreach (var d in data)
      {
          using (var processor = new Processor(d))
          {
              processor.Completed += (sender, e) =&gt; { // Do something else };
              tasks.Add(processor.ProcessAsync());
          }
      }
  
      await Task.WhenAll(tasks);
  }
  </code></pre>
  
  <p>Re-writing the code as below results in the each Processor performing its processing and THEN being disposed, but it's not the most efficient way to run multiple Tasks that don't depend on one another.</p>
  
  <pre><code>async public Task ProcessData(IEnumerable&lt;int&gt; data)
  {
      foreach (var d in data)
      {
          using (var processor = new Processor(d))
          {
              processor.Completed += (sender, e) =&gt; { // Do something else };
              await processor.ProcessAsync();
          }
      }
  }
  </code></pre>
  
  <p>Can someone please explain why the first example is disposing 'early' and give an example of the best code pattern for this situation.</p>