我有一个3层架构并使用tcp套接字在传输层(TCP客户端)中发送一些数据这种方法使用BeginSend方法异步.
public void TransportData(Stream stream) { try { SetTransporterState(StateObject.State.SendingData); if (clientSock.Connected) { ASCIIEncoding asen = new ASCIIEncoding(); stream.Position = 0; byte[] ba = GetStreamAsByteArray(stream); if (clientSock.Connected) clientSock.BeginSend(ba,ba.Length,SocketFlags.None,new AyncCallback(SendData),clientSock); else throw new SockCommunicationException("Socket communication Failed"); } catch (SocketException sex) { throw sex; } catch (SockCommunicationException comex) { bool rethrow = ExceptionPolicy.HandleException(comex,"TransportLayerPolicy"); if (rethrow) { throw; } } } } catch (SocketException soex) { throw soex; } catch (SockCommunicationException comex) { bool rethrow = ExceptionPolicy.HandleException(comex,"TransportLayerPolicy"); if (rethrow) { throw; } } catch (Exception ex) { LoggingMessageHelper.LogDeveloperMessage(ex.Message + Environment.NewLine + ex.StackTrace,1,TraceEventType.Critical); bool rethrow = ExceptionPolicy.HandleException(ex,"TransportLayerPolicy"); if (rethrow) { throw; } } }
回调代码SendData()如下所示
private void SendData(IAsyncResult iar) { Socket remote = null; try { remote = (Socket)iar.AsyncState; try { int sent = remote.EndSend(iar); } catch (Exception ex) { throw ex; } if (remote.Connected ) { remote.BeginReceive(data,size,new AsyncCallback(ReceiveData),remote); } else throw new SockCommunicationException("Communication Failed"); } catch (SocketException soex) { throw new SockCommunicationException("Communication Failed"); } catch (SockCommunicationException comex) { bool rethrow = ExceptionPolicy.HandleException(comex,"TransportLayerPolicy"); if (rethrow) { throw; } }
当服务器断开连接时,客户端在发送一些数据之前不知道,因此Connected属性为true.然后行remote.BeginReceive()抛出我尝试捕获的SocketException并抛出一个自定义异常(sockCommunicationException).
但是,当我这样做时,我得到一个未处理的异常.我想通过业务层将此错误冒泡到UI.当在回调方法中引发这样的异常时,它会被引发到哪里?
如何避免此未处理的异常并将此异常冒泡到UI层.
请帮忙.
提前致谢!