C#中的调用堆栈限制 [英] Call Stack limitation in C#

查看:272
本文介绍了C#中的调用堆栈限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i wonder how much calls we can perform in stack in c# before we get stack overflow exception

所以我决定写下面的代码

so i decided to write the following code

    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,我就得到了stackoverflow,但是这个数字不是常数,所以它如何工作?

my question is how compiler decides to throw stack overflow exception is this about memory limitations? once i put 42995 i got stackoverflow but this number is not constant so how this works?

推荐答案

每个线程都有一个堆栈大小.程序主线程的预定义堆栈大小在exe文件中固定.您进行的每个递归调用都消耗了一部分堆栈.完成后,CLR会抛出StackOverflowException.对于控制台/图形程序,默认堆栈大小应为1mb的内存.您不能从程序内部使此内存更大"(可以使用 editbin.exe 从程序外部"进行更改).该内存不是动态的.它是固定的(从技术上讲,为此内存保留的地址空间是固定的,该内存实际上是Windows OS按需分配的,一次大约4kb,但始终由保留的地址空间决定).您可以创建具有所需堆栈大小的辅助线程.

Each thread has a stack size. The predefined stack size for the main thread of a program is fixed in the exe file. Each recursive call you make, you consume a little of this stack. When you finish it, the CLR throws a StackOverflowException. For Console/Graphical programs the default stack size should be 1mb of memory. You can't make this memory "bigger" from inside the program (you can use editbin.exe to change it from "outside" the program). This memory isn't dynamic. It is fixed (technically, the address space reserved for this memory is fixed, the memory is really allocated by the Windows OS on demand, probably 4kb at a time, but always up to the reserved address space). You can create secondary threads with the stack size you want.

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

Note that the handling of the stack in this way is a limitation of x86/x64 architecture, http://en.wikipedia.org/wiki/Stack-based_memory_allocation:

某些处理器系列(例如x86)具有用于处理当前正在执行的线程的堆栈的特殊指令.其他处理器系列(包括PowerPC和MIPS)没有显式的堆栈支持,而是依靠约定并将堆栈管理委托给操作系统的应用程序二进制接口(ABI).

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).

这篇关于C#中的调用堆栈限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆