C# 給TcpClient的Connect方法設置超時時間
阿新 • • 發佈:2018-12-26
nco gin ces 簡便 this .net cti cpc sta
var client = new TcpClient(); var result = client.BeginConnect("remotehost", this.Port, null, null); var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1)); if (!success) { throw new Exception("Failed to connect."); } // we have connected client.EndConnect(result);
.Net 4.5的簡便寫法
var client = new TcpClient(); if (!client.ConnectAsync("remotehost", remotePort).Wait(1000)) { // connection failure }
代碼出處: https://stackoverflow.com/questions/17118632/how-to-set-the-timeout-for-a-tcpclient
C# 給TcpClient的Connect方法設置超時時間