Monthly Archives: February 2012

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)
    {
        // ...
    }
}