Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9214701
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T02:01:42+00:00 2026-06-18T02:01:42+00:00

Assume the following synchronous code: try { Foo(); Bar(); Fubar(); Console.WriteLine(All done); } catch(Exception

  • 0

Assume the following synchronous code:

try
{
    Foo();
    Bar();
    Fubar();
    Console.WriteLine("All done");
}
catch(Exception e) // For illustration purposes only. Catch specific exceptions!
{
    Console.WriteLine(e);
}

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.
How would I achieve the same behavior?
What I mean with “same” is:

  1. Execute a handler for the exception, if one is thrown.
  2. Stop execution of the following methods, if an exception is thrown.

The only thing I was able to come up with is horrible:

var fooTask = FooAsync();
fooTask.ContinueWith(t => HandleError(t.Exception),
                     TaskContinuationOptions.OnlyOnFaulted);
fooTask.ContinueWith(
    t =>
    {
        var barTask = BarAsync();
        barTask.ContinueWith(t => HandleError(t.Exception),
                             TaskContinuationOptions.OnlyOnFaulted);
        barTask.ContinueWith(
            t =>
            {
                var fubarTask = FubarAsync();
                fubarTask.ContinueWith(t => HandleError(t.Exception),
                                       TaskContinuationOptions.OnlyOnFaulted);
                fubarTask.ContinueWith(
                    t => Console.WriteLine("All done"),
                    TaskContinuationOptions.OnlyOnRanToCompletion);
            }, 
            TaskContinuationOptions.OnlyOnRanToCompletion);
    }, 
    TaskContinuationOptions.OnlyOnRanToCompletion);

Please note:

  • I need a solution that works with .NET 4, so async/await is out of the question. However, if it would work with async/await feel free to show how.
  • I don’t need to use the TPL. If it is impossible with the TPL another approach would be OK, maybe with Reactive Extensions?
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T02:01:44+00:00Added an answer on June 18, 2026 at 2:01 am

    Here’s how it would work with async:

    try
    {
        await FooAsync();
        await BarAsync();
        await FubarAsync();
        Console.WriteLine("All done");
    }
    catch(Exception e) // For illustration purposes only. Catch specific exceptions!
    {
        Console.WriteLine(e);
    }
    

    This would work on .NET 4.0 if you installed the (prerelease) Microsoft.Bcl.Async package.


    Since you’re stuck on VS2010, you can use a variant of Stephen Toub’s Then:

    public static Task Then(this Task first, Func<Task> next)
    {
      var tcs = new TaskCompletionSource<object>();
      first.ContinueWith(_ =>
      {
        if (first.IsFaulted) tcs.TrySetException(first.Exception.InnerExceptions);
        else if (first.IsCanceled) tcs.TrySetCanceled();
        else
        {
          try
          {
            next().ContinueWith(t =>
            {
              if (t.IsFaulted) tcs.TrySetException(t.Exception.InnerExceptions);
              else if (t.IsCanceled) tcs.TrySetCanceled();
              else tcs.TrySetResult(null);
            }, TaskContinuationOptions.ExecuteSynchronously);
          }
          catch (Exception exc) { tcs.TrySetException(exc); }
        }
      }, TaskContinuationOptions.ExecuteSynchronously);
      return tcs.Task; 
    }
    

    You can use it as such:

    var task = FooAsync().Then(() => BarAsync()).Then(() => FubarAsync());
    task.ContinueWith(t =>
    {
      if (t.IsFaulted || t.IsCanceled)
      {
        var e = t.Exception.InnerException;
        // exception handling
      }
      else
      {
        Console.WriteLine("All done");
      }
    }, TaskContinuationOptions.ExcecuteSynchronously);
    

    Using Rx, it would look like this (assuming you don’t have the async methods already exposed as IObservable<Unit>):

    FooAsync().ToObservable()
        .SelectMany(_ => BarAsync().ToObservable())
        .SelectMany(_ => FubarAsync().ToObservable())
        .Subscribe(_ => { Console.WriteLine("All done"); },
            e => { Console.WriteLine(e); });
    

    I think. I’m not an Rx master, by any means. 🙂

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Assume the following code: public class Foo { public string Bar { get; set;
Assume the following code: Foo* p = new (std::nothrow) Foo(); 'p' will equal 0
Let's assume the following scenario in Java public interface Foo { Object bar(); }
Assume the following scenario: All data are in Sql Server tables. 1) An Execute
Assume that the following Perl code is given: my $user_supplied_string = &retrieved_from_untrusted_user(); $user_supplied_string =~
Assume the following code in a Grails controller: def action = { ClassName o
Assume following code, NSString *str=[[NSString alloc] initWithString:@sagar]; [str autorelease]; I have seen many times
Let's assume following code snippet: public class NotThatWellWrittenClass { public static void doSmth() {
Assume the following, (in-ns silly.fun) (def a 1) (defn fx [b] ((fn [c] (return-all-symbols))
let's assume following C code: // events.h enum Events {eOne, eTwo, eThree}; enum Events

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.