gpt4 book ai didi

C# - AsyncCallback 中的异常传播问题

转载 作者:太空狗 更新时间:2023-10-30 00:34:17 24 4
gpt4 key购买 nike

下面的代码是不言自明的,我的问题也很简单:
为什么 AsyncCallback 方法“HandleConnect”不向“Connect”方法传播异常
以及如何传播它?

    public void Connect(IPEndPoint endpoint, IVfxIpcSession session)
{
try
{
ipcState.IpcSocket.BeginConnect(ipcState.IpcEndpoint, HandleConnect, ipcState);
}

catch(Exception x)
{
ManageException(x.ToString()); //Never Caught, though "HandleConnect" blows a SocketException
}
}

private void HandleConnect(IAsyncResult ar)
{
// SocketException blows here, no propagation to method above is made.
// Initially there was a try/catch block that hided it and this is NOT GOOD AT ALL
// as I NEED TO KNOW when something goes wrong here.
ipcState.IpcSocket.EndConnect(ar);
}


1 - 我想这是很正常的行为。但我希望能全面解释为什么会这样,以及幕后到底发生了什么。

2 - 是否有任何(快速且简单的)方法通过我的应用传播异常?

预警 我知道这里的很多人都非常挑剔,我期待评论“你为什么不把 ManageException 直接放在“HandleConnect”方法中。好吧,长话短说,我们就说“我有我的理由”哈哈。我刚刚在这里发布了一个代码示例,我想进一步传播这种异常方式,并且做的事情比“N-upper”代码中其他地方显示的更多。

编辑
作为对评论的回答,我之前确实也尝试过这个,但没有运气:

    private void HandleConnect(IAsyncResult ar) 
{
try
{
ipcState.IpcSocket.EndConnect(ar);
}

catch(Exception x)
{
throw x; // Exception Blows here. It is NOT propagated.
}
}

我的解决方案:我最终放置了一个事件处理程序,每个相关代码逻辑都订阅了该事件处理程序。
这样异常就不会被吞掉也不会被吹掉,而是会广播一个通知。

 public event EventHandler<MyEventArgs> EventDispatch;
private void HandleConnect(IAsyncResult ar)
{
try
{
ipcState.IpcSocket.EndConnect(ar);
}

catch(Exception x)
{
if (EventDispatch!= null)
{
EventDispatch(this, args);
}
}
}

//Priorly, I push subscriptions like that :

tcpConnector.EventDispatch += tcpConnector_EventDispatch;

public void tcpConnector_EventDispatch(object sender, VfxTcpConnectorEventArgs args)
{
//Notify third parties, manage exception, etc.
}

这有点歪,但效果很好

最佳答案

当您使用 BeginConnect 时,连接是异步完成的。您会得到以下事件链:

  1. Connect“发布”一个通过 BeginConnect 进行连接的请求。
  2. Connect 方法返回。
  3. 连接在后台完成。
  4. HandleConnect 由框架使用连接结果调用。

当您到达第 4 步时,Connect 已经返回,因此 try-catch block 不再处于事件状态。这是您在使用异步实现时获得的行为。

Connect 中捕获异常的唯一原因是 BeginConnect 无法启动后台连接任务。这可以例如be if BeginConnect 在启动后台操作之前验证提供的参数,如果不正确则抛出异常。

您可以使用 AppDomain.UnhandledException事件以在中心位置捕获任何未处理的异常。一旦异常达到该级别,任何形式的恢复都可能难以实现,因为异常可能来自任何地方。如果您有恢复方法 - 尽可能接近原点捕获异常。如果您只记录/通知用户 - 在一个地方集中捕获通常会更好。

关于C# - AsyncCallback 中的异常传播问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8136779/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com