回调c#中未处理的异常错误

前端之家收集整理的这篇文章主要介绍了回调c#中未处理的异常错误前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个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层.

请帮忙.

提前致谢!

解决方法

是的,不起作用.回调是在线程池线程上执行的,没有人可以捕获异常.例如,您需要引发UI可以订阅的事件.需要编组,如果需要更新UI,UI代码需要使用Control.BeginInvoke()之类的东西.
原文链接:https://www.f2er.com/csharp/100128.html

猜你在找的C#相关文章