代码之家  ›  专栏  ›  技术社区  ›  György Andrasek

在哪里处理异步异常?

  •  9
  • György Andrasek  · 技术社区  · 15 年前

    请考虑以下代码:

    class Foo {
        // boring parts omitted
    
        private TcpClient socket;
    
        public void Connect(){
            socket.BeginConnect(Host, Port, new AsyncCallback(cbConnect), quux);
        }
    
        private void cbConnect(IAsyncResult result){
                // blah
        }
    }
    

    如果 socket 在之后引发异常 BeginConnect 返回和之前 cbConnect 接到电话,它从哪里弹出?是否允许它在后台抛出?

    2 回复  |  直到 15 年前
        1
  •  7
  •   Yauheni Sivukha    15 年前

    来自的异步委托的异常处理的代码示例 msdn forum . 我认为tcpclient模式将是相同的。

    using System;
    using System.Runtime.Remoting.Messaging;
    
    class Program {
      static void Main(string[] args) {
        new Program().Run();
        Console.ReadLine();
      }
      void Run() {
        Action example = new Action(threaded);
        IAsyncResult ia = example.BeginInvoke(new AsyncCallback(completed), null);
        // Option #1:
        /*
        ia.AsyncWaitHandle.WaitOne();
        try {
          example.EndInvoke(ia);
        }
        catch (Exception ex) {
          Console.WriteLine(ex.Message);
        }
        */
      }
    
      void threaded() {
        throw new ApplicationException("Kaboom");
      }
    
      void completed(IAsyncResult ar) {
        // Option #2:
        Action example = (ar as AsyncResult).AsyncDelegate as Action;
        try {
          example.EndInvoke(ar);
        }
        catch (Exception ex) {
          Console.WriteLine(ex.Message);
        }
      }
    }
    
        2
  •  4
  •   JaredPar    15 年前

    如果接受连接的过程导致错误,将调用cbconnect方法。但要完成连接,您需要拨打以下电话

    socket.EndConnection(result);
    

    此时,BeginConnect进程中的错误将显示在引发的异常中。