David Dury David Dury - 3 months ago 56
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)


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

Jon Jon

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

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