public static bool TryConnect([NotNull] this Socket socket, [NotNull] EndPoint remoteEndpoint, int millisecondsTimeout) { socket = socket.ArgumentNotNull(); remoteEndpoint = remoteEndpoint.ArgumentNotNull(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { using (var mre = new ManualResetEventSlim(false)) { using (var sea = new SocketAsyncEventArgs() { RemoteEndPoint = remoteEndpoint, UserToken = mre }) { sea.Completed += (s, e) => ((ManualResetEventSlim)e.UserToken).Set(); var pending = socket.ConnectAsync(sea); if (!pending || mre.Wait(millisecondsTimeout)) { return(sea.SocketError == SocketError.Success); } Socket.CancelConnectAsync(sea); // this will close the socket! // In case of time-out, ManualResetEventSlim is left un-disposed to avoid race conditions, // letting SafeHandle's finalizer to do the cleanup. return(false); } } } else { throw new PlatformNotSupportedException(); } }