public static TcpClient ConnectWithTimeout(string ip, int port, int timeout) { var socket = new TcpClient(); var result = socket.BeginConnect(ip, port, null, null); if (!result.AsyncWaitHandle.WaitOne(timeout, true)) { Disposer.Dispose(socket); Thrower.Throw("Timeout connecting to {0}:{1}", ip, port); } socket.EndConnect(result); return(socket); }
public static SslStream SslWithTimeout(TcpClient client, int timeout) { var endpoint = client.Client.RemoteEndPoint; var stream = new SslStream(client.GetStream(), false, AcceptAnyCertificate); var result = stream.BeginAuthenticateAsClient(string.Empty, null, null); if (!result.AsyncWaitHandle.WaitOne(timeout, true)) { Disposer.Dispose(stream); Disposer.Dispose(client); Thrower.Throw("Timeout authenticating to {0}", endpoint); } return(stream); }