C# 中的调用堆栈限制

Call Stack limitation in C#

我想知道在出现堆栈溢出异常之前我们可以在 c# 中的堆栈中执行多少次调用

所以我决定写下面的代码

    static void Method2(int Calls)
    {
        if(!Calls.Equals(0))
            Method1(--Calls);//if more calls remain call method1 and reduce counter
    }
    static void Method1(int Calls)
    {
        if (!Calls.Equals(0))//if more calls remain call method2 and reduce counter
            Method2(--Calls);

    }
    static void Main(string[] args)
    {
        var Calls= 42994;//number of calls(stack overflow appears for large number)
        Method1(Calls);
    }

我的问题是编译器如何决定抛出堆栈溢出异常 这是关于内存限制吗? 一旦我输入 42995,我得到了 Whosebug,但是这个数字不是常数,所以这是如何工作的?

每个线程都有一个堆栈大小。程序主线程的预定义堆栈大小在 exe 文件中是固定的。您进行的每次递归调用都会消耗一点堆栈。当您完成它时,CLR 会抛出一个 WhosebugException。对于 Console/Graphical 程序,默认堆栈大小应为 1mb 内存。你不能从程序内部使这个记忆"bigger"(你可以使用editbin.exe从"outside"程序中改变它)。此内存不是动态的。它是固定的(从技术上讲,为这块内存保留的地址space是固定的,内存实际上是由WindowsOS按需分配的,一次大概4kb,但总是最多保留地址 space)。您可以创建具有所需堆栈大小的辅助线程。

请注意,以这种方式处理堆栈是 x86/x64 体系结构的限制,http://en.wikipedia.org/wiki/Stack-based_memory_allocation

Some processors families, such as the x86, have special instructions for manipulating the stack of the currently executing thread. Other processor families, including PowerPC and MIPS, do not have explicit stack support, but instead rely on convention and delegate stack management to the operating system's application binary interface (ABI).