Socket.Connect never returns

I read about the Problem that Socket.Connect might block forever.
I solved this with the following code:

/// <summary>
/// Opens a Tcp client connection
/// </summary>
/// <param name="ip">Server ip address</param>
/// <param name="port">Server port</param>
/// <param name="timeout">Timeout in milliseconds</param>
/// <returns>Returns the Tcp socket</returns>
public static Socket OpenTcpClient(IPAddress ip, int port, int timeout)
{
   var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
   if (timeout < 0)
   {
      socket.Connect(new IPEndPoint(ip, port));
   }
   else
   {
      var doneEvent = new ManualResetEvent(false);
      Exception connectException = null;
      var thread = new Thread(() =>
      {
         try
         {
            socket.Connect(new IPEndPoint(ip, port));
            doneEvent.Set();
         }
         catch (Exception ex)
         {
            connectException = ex;
            try
            {
               doneEvent.Set();
            }
            catch
            {}
         }
      });
      thread.Start();
      try
      {
         if (doneEvent.WaitOne(timeout, false))
         {
            if (connectException != null)
            {
               throw connectException;
            }
         }
         else
         {
            throw new TimeoutException();
         }
      }
      finally
      {
         if (thread.IsAlive)
         {
            try
            {
               thread.Abort();
            }
            catch { }
         }
      }
   }
   return socket;
}

Can anyone tell me if this is the right way to do handle this issue?

I mean, it is working, but I’m not verry experianced in aborting threads.

Have a look here for an alternative solution.

https://www.ghielectronics.com/community/forum/topic?id=12496

I used this recently for the exact same issue on a Cobra 2.

A quick glance at your code says it should work as long as your timeout is > 0 otherwise the option for timeout < 0 will block forever if there is no end point listening.

Well, my intention was to have the ‘normal’ behaviour if timeout is set to infinite (-1).