简体   繁体   English

我应该如何处理在使我变得同步的异步方法期间引发的异常?

[英]How should I handle exceptions that are thrown during asynchronous methods that I've made syncrhonous?

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. 我想从我的方法中抛出一个异常,服务器的异常为其InnerException。 However, in order to capture the exception, I have to box it up, and it seems like there should be an easier way. 但是,为了捕获异常,我必须将其装箱,似乎应该有一种更简单的方法。 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...
    }
}

There's nothing intrinsically wrong with passing back a boxed exception from an external process, particularly if you have nested inner exceptions or need the stack trace. 从外部进程中返回装箱的异常并没有本质上的错误,特别是如果您嵌套了内部异常或需要堆栈跟踪时。 If you're only interested in the exception messages, you could simply things by concatenating them into a string and only pass that back. 如果您只对异常消息感兴趣,则可以将它们串联成一个字符串,然后仅将其传递回去。

You are making it kinda hard on yourself by putting the lambda in its own method. 通过将lambda放入其自己的方法中,您会觉得自己有些困难。 It gets to be a lot easier if you write it inline. 如果您内联编写,它将变得容易得多。 Something like this: 像这样:

        var waitHandle = new ManualResetEvent(false);
        Exception fault = null;
        bool called = theServer.ServerMethod((obj, se) => {
            if (se.Exception != null) fault = se.Exception;
            else ProcessServerResponse(se);
            waitHandle.Set();
        });
        if (called) {
            waitHandle.WaitOne();
            if (fault != null) kaboom(fault);
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM