7

The Windows Internal book 5th edition has the following comment in page 360.

The stack size for the initial thread is taken from the image—there’s no way 
to specify another size.

I understand that for Windows OS, each thread is given 4K or 16K (depending on system) stack, and the size is fixed.

Then how about the stack in .NET?

  • How big is the stack?
  • The size of the stack is fixed or variable?
  • Is the stack allocated for each thread just like the case of Windows?
prosseek
  • 182,215
  • 215
  • 566
  • 871
  • related: http://stackoverflow.com/questions/1042345/how-do-you-change-default-stack-size-for-managed-executable-net – Mitch Wheat Nov 03 '10 at 15:11

2 Answers2

9

Yes, the size for the startup thread is determined by a value in the .EXE file header. Necessarily so, it is the OS that creates the thread, before any code in the program can run. It calls the entrypoint of the program, CorExeMain().

The managed compiler you use writes that value into the EXE file header. Current .NET compilers select 1 MB when you target x86 or Any CPU, 4 MB when you target x64. This is however not fixed, you can modify the value with the Editbin.exe utility, /STACK command line option. You could use this post-build event to get a 2MB stack:

  set path=%path%;$(DevEnvDir);$(DevEnvDir)..\..\vc\bin
  editbin.exe /STACK:2097152 "$(TargetPath)"

The stack size for threads that you create yourself are under your control, the Thread class constructor has overloads that lets you specify the size. You cannot make it too small, if clips the value to 256 KB. That's necessary, the just-in-time compiler also uses the stack.

Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
0

Here's a similar discussion on the topic.

Question

The documentation indicates that the threads "default stack size" is 1MB. The work "default" implies that it can be changed.

Is it possible to change the StackSize in .NET? If so how?

Answer

Unfortunately no. The documentation you were reading was for the creation of new threads in the system, which is handled by the Thread class. The CreateThread API function allows you to set the stack size and you can call it from .NET. However, I don't know if that is a good idea, since I am not sure how the runtime will perceive that thread.

Here is a code sample for creating threads using the CreateThread API

http://www.codeproject.com/KB/threads/Threads_1.aspx

Robert Greiner
  • 29,049
  • 9
  • 65
  • 85