Asynchronous Delegates: Catching Exceptions

Consult any C# reference regarding asynchronous delegates, and you will be assured that you can catch any exception thrown by an asynchronous delegate so long as you call EndInvoke() on the delegate reference.

I assembled a quick test, explicitly throwing an exception within the asynchronously invoked method, and the debugger routinely flagged the exception as unhandled. Convinced I had done something wrong, I stopped the debugger, combed over my code, and checked more C# resources. Everything looked correct.

Suddenly, it occurred to me to try running the application outside the debugger. The clouds parted. The call to EndInvoke() was rethrowing the exception from the asynchronous delegate after all! I then went back to the bugger, continued stepping through the code past the “unhandled exception,” and sure enough, the call to EndInvoke() was delivering the goods all along.

public void MethodAsync()
{
    Action action = Method;
    IAsyncResult result = action.BeginInvoke(MethodComplete, null);
}

private void Method()
{
    throw new Exception("Fail.");
}

private void MethodComplete(IAsyncResult result)
{
    Action action = (Action)((AsyncResult)result).AsyncDelegate;
            
    try
    {
        action.EndInvoke(result);
    }
    catch (Exception ex)
    {
        // ...
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: