Where do I handle asynchronous exceptions?

前端 未结 2 518
别那么骄傲
别那么骄傲 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 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);
        }
      }
    }
    

提交回复
热议问题