views:

71

answers:

2

Consider the following 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
    }
}

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?

A: 

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.

JaredPar
+2  A: 

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