6

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-line/console). So I am kind of guessing its something to do with the default stack size allocated in UI thread to that of in Powershell (command line/console).

So how to find current thread's maximum stack size?

I know ideally one doesn't need to know these or set these, but looks like its related to stack size as it works from console/Powershell(command-line app) not from UI.

The below thread is kind of related, but it doesn't answer my question; it probably gives some guidelines:

Maximum Thread Stack Size .NET?

To get more details about the actual problem:

StackOverFlowException: Is it programming error (recursion) or not enough maximum default stack size?

halfer
  • 19,824
  • 17
  • 99
  • 186
Dreamer
  • 3,371
  • 2
  • 34
  • 50

2 Answers2

6

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

Michael Ganß
  • 2,846
  • 1
  • 18
  • 11
2

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.

ken2k
  • 48,145
  • 10
  • 116
  • 176