2

I'm currently calling an async method and don't want to await it. I don't need the result for the async method and don't want to block during IO. However, if there is an error thrown in the async method I would like to catch it. So far I have:

public static void main () {
    MyAsyncMethod().
    ContinueWith(t => Console.WriteLine(t.Exception),
           TaskContinuationOptions.OnlyOnFaulted);
    //dostuff without waiting for result
}

This is not catching the exception thrown in MyAyncMethod from Main. Is there something I'm doing wrong?

3
  • There's no try-catch block...? Commented Oct 26, 2015 at 21:09
  • If it's "not catching the exception" what does happen? Commented Oct 26, 2015 at 21:13
  • I assumed that Continuewith would "catch" the exception. Atleast, that's what I read but currently my code crashes Commented Oct 26, 2015 at 22:54

1 Answer 1

2

async-await and ContinueWith can work but it is full of headaches. It is much easier just refactor out your error handling in to a method and put it in there, then you can just call that new method from your main method.

public static void main () {
    var task = DoMyAsyncMethod();

   //dostuff without waiting for result

    //Do a wait at the end to prevent the program from closing before the background work completes. 
    task.Wait();

}

private static async Task DoMyAsyncMethod()
{
    try
    {
        await MyAsyncMethod();
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }
}

I suspect the real problem you are dealing with is that missing Wait() and your program is closing itself before your background work is done processing.

Sign up to request clarification or add additional context in comments.

2 Comments

Our program will always be running on a server so we will never wait. Won't this still block in DoMyAsyncMethod ?
No, when you hit the await the function DoMyAsyncMethod will retun a Task object, it will not block. It is up to you want you want to do with that Task, wait on it, throw it away, it does not matter. A await really is just a easier way to do work with a ContinueWith, it lets you write async code the same way you write sync code (for example, using a try/catch instead of a ContinueWith(SomeMethod, TaskContinuationOptions.OnlyOnFaulted)).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.