在哪里处理异步异常?

2024-02-08

考虑以下代码:

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
    }
}

If socket之后抛出异常BeginConnect返回和之前cbConnect被调用,它在哪里弹出?是否允许将其放入后台?


异步委托异常处理的代码示例msdn论坛 http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/750e0076-73a0-4a1d-b23a-93738ceed382。我相信 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);
    }
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在哪里处理异步异常? 的相关文章

随机推荐