Consider the following code:
class Foo {
// boring parts omitted
private TcpClient socket;
public void Connect(){
socket.BeginConnect(Host,
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.
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);
}
}
}