Where do I handle asynchronous exceptions?

前端 未结 2 516
别那么骄傲
别那么骄傲 2021-02-08 14:42

Consider the following code:

class Foo {
    // boring parts omitted

    private TcpClient socket;

    public void Connect(){
        socket.BeginConnect(Host,         


        
相关标签:
2条回答
  • 2021-02-08 14:54

    If the process of accepting a connection results in an error your cbConnect method will be called. To complete the connection though you'll need to make the following call

    socket.EndConnection(result);
    

    At that point the error in the BeginConnect process will be manifested in a thrown exception.

    0 讨论(0)
  • 2021-02-08 15:09

    Code sample of exception handling for asynch delegate from msdn forum. I beleive that for TcpClient pattern will be the same.

    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);
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题