Search code examples
c#multithreadingexceptionstack-overflow

Thread used for TCP Listening throws StackoverflowException


I'm having problems listening for connections within a TCPListener, basically I am running this on a different thread as so:

listenThread = new Thread(new ThreadStart(Listen));

void Listen(...)
{
    while (true)
    {
        Socket socket = Listener.AcceptSocket(); 
        Connection connection = new Connection(socket);
        connection.onInit();
        Thread.Sleep(100);
        Listen();
    }
}

I have no idea what to do next to solve this "Stackoverflow" Exception, I need to listen to connections on a different thread like the way I've coded it, any suggestions to fix it?


Solution

  • Listen() is calling itself which will eventually result in a stack overflow.

    Simply remove the call to Listen() at end of the while loop.