David Dury David Dury - 1 month ago 25
C# Question

TcpClient ConnectAsync get status

Is there any way I can get the status of a TcpClient async connection? Using the following code, how can I get the status of the client using the Connected property? I try to establish a remote connection asynchronously but in the same time don't wait more then 5 seconds ...

TcpClient client = new TcpClient();

Task tsk = Task.Factory.StartNew(() =>
{
client.ConnectAsync(host, port);

// client.Connect (this is always false)
});

tsk.Wait(5000);

// client.Connect (or if I use it here, this is always false)

Jon Jon
Answer

First off, do not create a new Task of your own; this is a bug. ConnectAsync already returns a Task that represents the connection attempt:

var tsk = client.ConnectAsync(host, port);
tsk.Wait(5000);

After the wait returns, check the IsCompleted property of the task; it will be true if and only if the connection was established.