Runtime exception, recursion too deep

后端 未结 12 1065
余生分开走
余生分开走 2020-12-19 04:59

I converted the pseudo-code here into C#, and have it recursively repeat 10,000 times. But I get a C# runtime error, StackOverflow Exception after 9217

12条回答
  •  没有蜡笔的小新
    2020-12-19 05:31

    The recursive call is not tail-recursive, and even if it were, it wouldn't help since the C# compiler does not currently optimize tail-recursive calls. EDIT: As pointed out by Eric Lippert and Gabe, the CLR could choose to generate tail calls even when explicit tail-call instructions are not in the emitted IL.

    1. The best way would be to turn this recursive solution into an iterative one.
    2. Since it almost completes, a quick hack might be to increase the stack-size of the thread on which this method runs.

    Please don't do this. For fun only:

    static void Main()
    {
        Console.WriteLine(SafeCalculatePi(10000));
    }
    
    // Calculates PI on a separate thread with enough stack-space 
    // to complete the computation
    public static double SafeCalculatePi(int maxRecursion)
    {
        // We 'know' that you can reach a depth of 9217 for a 1MB stack.
        // This lets us calculate the required stack-size, with a safety factor
        double requiredStackSize = (maxRecursion / 9217D) * 1.5 * 1024 * 1024 ; 
    
        double pi = 0;
        ThreadStart ts = delegate { pi = CalculatePi(maxRecursion); };
        Thread t = new Thread(ts, (int)requiredStackSize);
        t.Start();
        t.Join();
        return pi;
    }
    

提交回复
热议问题