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.Connect (this is always false)
// client.Connect (or if I use it here, this is always false)
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.