Search code examples
.netrecursionstack-overflowtcpclient

Stack Overflow on TcpClient (Recursion)


Because of the repeated calls to new, the following code may produce a stack overflow exception if left as-is:

async void Connect()
{
    try 
    {
        client = new TcpClient(ip, port);
    }
    catch (Exception e)
    {
        HandleException(e); // Most likely will be a SocketException e.g. connection refused
        Connect(); // Try to connect again
    }
}

While I could reduce the chances of this happening by e.g. adding a maximum number of retries before giving up and exiting the recursion, I'd rather write it so that memory is freed and stack overflow exceptions don't happen.

I thought about putting it in a while loop, but I think that will have the same problem, e.g.

while (!connected)
{
    try
    {
        client = new TcpClient(ip, port);
        connected = true;
    }
    catch (Exception e)
    {
        HandleException(e);
    }
}

Is there a better way to avoid stack overflow exceptions here aside from having an arbitrarily defined maximum number of retries?


Solution

  • As Lasse said in his comments:

    a. The loop does not have the same behaviour as recursion when it comes to memory and scope, so using that is safer here.

    b. It's always technically possible to run into stack overflow exceptions, but some approaches like recursion are typically more prone to it than regular loops.

    I have ultimately implemented a loop with some extra conditions for e.g. max number of retries.