不,@Jon錯了! IsCompleted
只會告訴你,如果任務已完成,它不會而不是表明連接已完成。例如,如果沒有服務器在特定地址/端口上打開,則IsCompleted
將返回true
...您應該檢查IsFaulted
。
這裏是代碼,我已經從互聯網上的作品放在一起,其實我已經測試:
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
}
另一種辦法是檢查是'等待()'結果。 – svick