title: Sequential processing of asynchronous tasks
body: <p>Assume the following synchronous code:</p>
  
  <pre><code>try
  {
      Foo();
      Bar();
      Fubar();
      Console.WriteLine("All done");
  }
  catch(Exception e) // For illustration purposes only. Catch specific exceptions!
  {
      Console.WriteLine(e);
  }
  </code></pre>
  
  <p>Now assume all these methods have an Async counterpart and I have to use those for some reason, so simply wrapping the whole thing in a new task is not an option.<br>
  How would I achieve the same behavior?<br>
  What I mean with "same" is:</p>
  
  <ol>
  <li>Execute a handler for the exception, if one is thrown.</li>
  <li>Stop execution of the following methods, if an exception is thrown.</li>
  </ol>
  
  <p>The only thing I was able to come up with is <strong><em>horrible</em></strong>:</p>
  
  <pre><code>var fooTask = FooAsync();
  fooTask.ContinueWith(t =&gt; HandleError(t.Exception),
                       TaskContinuationOptions.OnlyOnFaulted);
  fooTask.ContinueWith(
      t =&gt;
      {
          var barTask = BarAsync();
          barTask.ContinueWith(t =&gt; HandleError(t.Exception),
                               TaskContinuationOptions.OnlyOnFaulted);
          barTask.ContinueWith(
              t =&gt;
              {
                  var fubarTask = FubarAsync();
                  fubarTask.ContinueWith(t =&gt; HandleError(t.Exception),
                                         TaskContinuationOptions.OnlyOnFaulted);
                  fubarTask.ContinueWith(
                      t =&gt; Console.WriteLine("All done"),
                      TaskContinuationOptions.OnlyOnRanToCompletion);
              }, 
              TaskContinuationOptions.OnlyOnRanToCompletion);
      }, 
      TaskContinuationOptions.OnlyOnRanToCompletion);
  </code></pre>
  
  <p>Please note:</p>
  
  <ul>
  <li>I need a solution that works with .NET 4, so <code>async/await</code> is out of the question. However, if it would work with <code>async/await</code> feel free to show how.</li>
  <li>I don't need to use the TPL. If it is impossible with the TPL another approach would be OK, maybe with Reactive Extensions?</li>
  </ul>