Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching an exception thrown in an asynchronous callback

I have a method that takes a callback argument to execute asynchronously, but the catch block doesn't seem to be catching any exceptions thrown by the synchronous call (this.Submit refers to a synchronous method).

public void Submit(FileInfo file, AnswerHandler callback)
{
    SubmitFileDelegate submitDelegate = new SubmitFileDelegate(this.Submit);
    submitDelegate.BeginInvoke(file, (IAsyncResult ar) =>
    {
        string result = submitDelegate.EndInvoke(ar);
        callback(result);
    }, null);
}

Is there a way to catch the exception thrown by the new thread and send it to the original thread? Also, is this the "proper" way to handle async exceptions? I wrote my code so it could be called like this (assuming the exception issue is fixed):

try
{
    target.Submit(file, (response) =>
    {
        // do stuff
    });
}
catch (Exception ex)
{
    // catch stuff
}

but is there a more proper or elegant way to do this?

like image 762
kevmo314 Avatar asked Jan 05 '12 19:01

kevmo314


People also ask

What happens if an exception is thrown within an asynchronous method?

As we know, in asynchronous programming, control does not wait for the function's result and it executes the next line. So when the function throws an exception, at that moment the program control is out of the try-catch block.

What happens when a catch handler throws an exception?

By throwing an exception, the method can bypass the need for any return -- sending out an error message (via an exception object) instead) The calling module (whoever called the function) would have to "catch" the exception, to discover what occurred.

How do you handle catching exception?

The first catch block that handles the exception class or one of its superclasses will be executed. So, make sure to catch the most specific class first. If an exception occurs in the try block, the exception is thrown to the first catch block. If not, the Java exception passes down to the second catch statement.

Can callbacks be synchronous?

Summary. The callback is a function that's accepted as an argument and executed by another function (the higher-order function). There are 2 kinds of callback functions: synchronous and asynchronous. The synchronous callbacks are executed at the same time as the higher-order function that uses the callback.


2 Answers

In short, no.

When you call submitDelegate.BeginInvoke, it spawns the new thread, returns, and promptly exits your try/catch block (while the new thread runs in the background).

You could, however, catch all unhandled exceptions like this:

AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(YourException);

This will catch everything in the application domain, however (not just your async method).

like image 184
Mark Avenius Avatar answered Oct 09 '22 18:10

Mark Avenius


If you're targeting .NET 4.0, you can utilize the new Task Parallel Library, and observe the Task object's Exception property.

public Task Submit(FileInfo file)
{
    return Task.Factory.StartNew(() => DoSomething(file));
}

private void DoSomething(FileInfo file)
{
    throw new Exception();
}

Then use it like this:

Submit(myFileInfo).ContinueWith(task =>
{
    // Check task.Exception for any exceptions.

    // Do stuff with task.Result
});

where DoSomething is the method you'd like call asynchronously, and the delegate you pass to ContinueWith is your callback.

More information about exception handling in TPL can be found here: http://msdn.microsoft.com/en-us/library/dd997415.aspx

like image 22
Adi Lester Avatar answered Oct 09 '22 19:10

Adi Lester