我有一个 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, 0, 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, 0, size, SocketFlags.None,
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 层。
请帮忙。
提前致谢!