No, @Jon is wrong! The IsCompleted
will just tell you if the task has been completed, it doesn't not indicate that the connection has been made. For example, if no server is open on the specific address/port, IsCompleted
will return true
anyway... You should check IsFaulted
instead.
Here is code, that I have put together from pieces of the internet and I have actually tested:
string address = "127.0.0.1";
int port = 8888;
int connectTimeoutMilliseconds = 1000;
var tcpClient = new TcpClient();
var connectionTask = tcpClient
.ConnectAsync(address, port).ContinueWith(task => {
return task.IsFaulted ? null : tcpClient;
}, TaskContinuationOptions.ExecuteSynchronously);
var timeoutTask = Task.Delay(connectTimeoutMilliseconds)
.ContinueWith<TcpClient>(task => null, TaskContinuationOptions.ExecuteSynchronously);
var resultTask = Task.WhenAny(connectionTask, timeoutTask).Unwrap();
resultTask.Wait();
var resultTcpClient = resultTask.Result;
// Or shorter by using `await`:
// var resultTcpClient = await resultTask;
if (resultTcpClient != null)
{
// Connected!
}
else
{
// Not connected
}