如何更改 .NET 程序的堆栈大小?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2556938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change stack size for a .NET program?
提问by Frank
I have a program that does recursive calls for 2 billion times and the stack overflow. I make changes, and then it still need 40K recursive calls. So I need probably several MB stack memory. I heard the stack size is default to 1MB. I tried search online. Some one said to go properties ->linker .........in visual studio, but I cannot find it.
我有一个程序可以执行 20 亿次递归调用和堆栈溢出。我进行了更改,然后它仍然需要 40K 递归调用。所以我可能需要几 MB 堆栈内存。我听说堆栈大小默认为 1MB。我试过网上搜索。有人说在visual studio中转到属性->链接器……但我找不到它。
Does anybody knows how to increase it? Also I am wondering if I can set it somewhere in my C# program?
有人知道怎么增加吗?另外我想知道我是否可以在我的 C# 程序中设置它?
P.S. I am using 32-bit winXP and 64bit win7.
PS 我使用的是 32 位的 winXP 和 64 位的 win7。
回答by Andrew O'Reilly
The easiest way to set the stack size from .NET 2.0 and Win XP onwards is to spawn a new thread with the stack size you'd like:-
从 .NET 2.0 和 Win XP 开始设置堆栈大小的最简单方法是使用您想要的堆栈大小生成一个新线程:-
using System.Threading;
Thread T = new Thread(threadDelegate, stackSizeInBytes);
T.Start();
To change the stack size of the entire program you'd have to use editbin:-
要更改整个程序的堆栈大小,您必须使用 editbin:-
EDITBIN.EXE /STACK:<stacksize> file.exe
回答by Reed Copsey
There is no compiler option to do it. You can edit it after the fact using editbin /stack, or create a separate thread for your algorithm, and specify a larger stack size in the Thread constructor.
没有编译器选项可以做到这一点。您可以事后使用 editbin /stack 对其进行编辑,或者为您的算法创建一个单独的线程,并在Thread 构造函数中指定更大的堆栈大小。
That being said, you may want to flatten your recursive function... If you're having stack overflows now, it's tough to know that any stack size will be appropriate in the long term. This is just a band-aid solution.
话虽如此,您可能想要展平您的递归函数……如果您现在遇到堆栈溢出,很难知道从长远来看任何堆栈大小都是合适的。这只是创可贴解决方案。
回答by John Boker
Most likely you should try to use loops instead of recursion.
您很可能应该尝试使用循环而不是递归。
回答by Puppy
I know that in VS you can set an arbitrary stack size (EDIT: For C++ programs). However, I'd suggest that you use a tail call (i.e., return MyFunc(args); ) which automatically recycles stack space. Then, you'd use some heap-allocated object to hold state.
我知道在 VS 中您可以设置任意堆栈大小(编辑:对于 C++ 程序)。但是,我建议您使用自动回收堆栈空间的尾调用(即 return MyFunc(args); )。然后,您将使用一些堆分配对象来保存状态。

