用递归替换while循环

Dan*_*rgl 0 c# sockets recursion tcpclient while-loop

快速简单的问题:

这是:

private static void SetupConnection()
{
    try
    {
        TcpClient client = new TcpClient(myServer, myPort);
        //Do whatever...
    }
    catch (SocketException)
    {
        //Server is closed. Retry in 10 minutes.
        Thread.Sleep(600000);
        SetupConnection();
    }
Run Code Online (Sandbox Code Playgroud)

一个可行的替代方案:

private static void SetupConnection()
{
    while (true)
    {
        try
        {
            TcpClient client = new TcpClient(myServer, myPort);
            //Do whatever...
            break;
        }
        catch (SocketException)
        {
            //Server is closed. Retry in 10 minutes.
            Thread.Sleep(600000);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

虽然第二个看起来"更干净",但如果第一个也是可以接受的话,我仍然很好奇 - 如果不是,那么为什么不呢?

Nic*_*ick 6

在这种情况下,递归很糟糕,因为如果程序运行时间太长而重试连接,最终会遇到StackOverflowException.