private void ListenForConnections() { try { // Start the listener listening for requests. tcpListener.Start(); while (enabled) { while (!tcpListener.Pending() && enabled) { Thread.Sleep(500); } // Make sure that while we were sleeping // the service wasn't enabled. // Also make sure that we are go for accepting // new connections. if (enabled) { // Get the socket. TcpClientSocket socket = new TcpClientSocket(tcpListener.AcceptSocket()); if (acceptNewConnections) { // Create a new Client Listener and pass through the callback ClientListener tcp = new ClientListener(socket, new ClientDisconnectedEventHandler(this.ClientDisconnectedCallback)); // Add the client listener to the collection clientsLock.AcquireWriterLock(Timeout.Infinite); try { connectedClients.Add(tcp); } finally { clientsLock.ReleaseLock(); } // Start the client listener. tcp.StartListening(); } else { // We simply close connections if we // are not accepting connections. socket.Close(); } // Sleep the current thread for a bit. Thread.Sleep(1); } } } catch (Exception ex) { this.enabled = false; Lib.log.Add("TcpConnectionListener.ListenForConnections exception", ex.Message + ex.StackTrace); } finally { tcpListener.Stop(); } }