我正在写一个同步方法,在另一台服务器上调用异步方法。服务器的方法在完成时调用回调函数,并且在出现错误的情况下,回调参数中的一个包含异常。我想从我的方法抛出一个异常,将服务器的异常作为它的InnerException。然而,为了捕捉到这个例外,我必须把它装箱,似乎应该有一个更简单的方法。这是代码味道吗?我应该怎么做更简单?我应该如何处理异步方法中引发的异常? (或者,这是一个代码的气味?)
我的代码是这样的:
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...
}
}
为真,但是不能使用编辑并继续。 – Simon