我在哪里可以处理异步异常?我在、异常

由网友(我怕是我自作多情)分享简介:考虑以下code:class Foo {// boring parts omittedprivate TcpClient socket;public void Connect(){socket.BeginConnect(Host, Port, new AsyncCallback(cbConnect), quux);}...

考虑以下code:

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

如果插槽 BeginConnect 收益和 cbConnect 被调用,在它弹出?它甚至允许抛出的背景是什么?

If socket throws an exception after BeginConnect returns and before cbConnect gets called, where does it pop up? Is it even allowed to throw in the background?

推荐答案

code异常的样品处理的异步委托从msdn论坛。我beleive对于TcpClient的图案将是相同的。

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