.NET 堆栈与 Windows 堆栈堆栈、NET、Windows

2023-09-07 02:58:19 作者:听够了珍惜

Windows Internal book 5th edition在页面中有如下评论360.

初始线程的堆栈大小取自图像——没有办法指定另一个尺寸.

据我了解,对于 Windows 操作系统,每个线程被赋予 4K 或 16K(取决于系统)堆栈,并且大小是固定的.

不想升Win10又怕系统崩,Win7延长支持服务了解一下

那么 .NET 中的堆栈呢?

堆栈有多大?栈的大小是固定的还是可变的?是否像 Windows 一样为每个线程分配堆栈?

解决方案

是的,启动线程的大小由 .EXE 文件头中的值决定.必然如此,创建线程的是操作系统,在程序中的任何代码都可以运行之前.它调用程序的入口点,CorExeMain().

您使用的托管编译器将该值写入 EXE 文件头.当前的 .NET 编译器在以 x86 或 Any CPU 为目标时选择 1 MB,在以 x64 为目标时选择 4 MB.然而,这不是固定的,您可以使用 Editbin.exe 实用程序/STACK 命令行选项修改该值.您可以使用此构建后事件来获取 2MB 堆栈:

 设置路径=%path%;$(DevEnvDir);$(DevEnvDir)....vcineditbin.exe/STACK:2097152 "$(TargetPath)"

您自己创建的线程的堆栈大小由您控制,线程类构造函数 具有允许您指定大小的重载.如果将值裁剪为 256 KB,则不能使其太小.这是必要的,即时编译器也使用堆栈.

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?

解决方案

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

 
精彩推荐