You'll need to create a new AsyncCallback
and set it to a specific void where something will be done once the TcpClient
is finished connecting to the host. You might also want to check whether the TcpClient
connection succeeded or not by checking the value of the TcpClient.Connected
Example
The following example illustrates the asynchronous TcpClient
connection to google.com on port 80
static TcpClient cli = new TcpClient(); //Initialize a new TcpClient
static void Main(string[] args)
{
send("Something");
Console.ReadLine();
}
private static void doSomething(IAsyncResult result)
{
if (cli.Connected) //Connected to host, do something
{
Console.WriteLine("Connected"); //Write 'Connected'
}
else
{
//Not connected, do something
}
Console.ReadLine(); //Wait for user input
}
private static void send(string msg)
{
AsyncCallback callBack = new AsyncCallback(doSomething); //Set the callback to the doSomething void
cli.BeginConnect("google.com", 80, callBack, cli); //Try to connect to Google on port 80
}
Here's a better way to do what you described in the comment
System.Threading.Thread newThread = new System.Threading.Thread((System.Threading.ThreadStart)delegate {
//Do whatever you want in a new thread
while (!cli.Connected)
{
//Do something
}
});
newThread.Start(); //Start executing the code inside the thread
//This code will still run while the newThread is running
Console.ReadLine(); //Wait for user input
newThread.Abort(); //Stop the thread when the user inserts any thing