I'm writing a synchronous method that calls an asynchronous method on another server. The server's method calls a callback when it's done, and in case of error one of the callback's arguments contains an exception. I'd like to throw an exception from my method, with the server's exception as its InnerException. However, in order to capture the exception, I have to box it up, and it seems like there should be an easier way. Is this a code smell? What should I be doing more simply?
My code works like this:
private class BoxedException
{
public Exception Exception;
}
public bool MyMethod()
{
EventWaitHandle waitHandle = new new EventWaitHandle(false, EventResetMode.ManualReset);
BoxedException boxedException = new BoxedException();
bool called = theServer.ServerMethod(getCallback(waitHandle, boxedException));
if (called)
{
waitHandle.WaitOne();
if (boxedException.Exception != null)
throw new Exception("ServerMethod failed", boxedException.Exception);
}
}
private ServerCallback getCallback(EventWaitHandle waitHandle, BoxedException be)
{
return (object sender, ServerArgs e) =>
{
handleServerArgs(e, be);
waitHandle.Set();
};
}
private void handleServerArgs(ServerArgs e, BoxedException be)
{
if (e.Exception != null)
{
be.Exception = e.Exception;
}
else
{
// do stuff...
}
}