How to find current thread's max stack size in .net?

前端 未结 2 1789
暖寄归人
暖寄归人 2021-01-12 18:39

How can I find current thread\'s maximum stack size?

I am getting a stack overflow exception while executing a function from MMC UI but not from Powershell (command-

相关标签:
2条回答
  • 2021-01-12 19:05

    Getting this information is a real PITA actually:

    1. Get the thread ID using GetCurrentThreadId
    2. Use OpenThread to get a handle to the thread
    3. Now use NtQueryInformationThread to get information about the thread. You'll use ThreadBasicInformation as THREADINFOCLASS to get a THREAD_BASIC_INFORMATION structure. You now have the TebBaseAddress parameter that is the address of the Thread Environment Block.
    4. Read in process memory at the TebBaseAddress address.
    5. Within the Thread Environment Block (TEB), you have access to the StackLimit property which is the value you're looking for.

    From step 3, it's undocumented. That's why I do not recommend retrieving this information.

    0 讨论(0)
  • 2021-01-12 19:07

    From Windows 8, there is the GetCurrentThreadStackLimits() function. You can use it from C# via PInvoke like this:

    [DllImport("kernel32.dll")]
    static extern void GetCurrentThreadStackLimits(out uint lowLimit, out uint highLimit);
    
    uint low;
    uint high;
    
    GetCurrentThreadStackLimits(out low, out high);
    var size = (high - low) / 1024; // in KB
    

    On my machine, this yields 1MB in a console application, 256KB in a web application (IIS).

    0 讨论(0)
提交回复
热议问题