Is it possible in C#, running on a Windows server, to create a thread with a maximum stack size that is lower than 256KB? -- Or whatever the default is for IIS; or more specifically, an Azure Web Site.
This console program that I wrote seems to show that it's not possible through the .NET Thread
constructor, and I haven't found any information on the web indicating that it's possible via P-Invoke or any other mechanisms.
Here's the program output on my Windows 10 desktop:
Default maximum stack size in bytes: 1,048,576
Expected maximum stack size in bytes: 64,000; Actual: 262,144
Expected maximum stack size in bytes: 128,000; Actual: 262,144
Expected maximum stack size in bytes: 512,000; Actual: 524,288
Expected maximum stack size in bytes: 2,048,000; Actual: 2,097,152
Expected maximum stack size in bytes: 1,024,000; Actual: 1,048,576
internal class Program
{
public static void Main()
{
var threads = new[]
{
CreateControlThread(),
CreateThread(64_000),
CreateThread(128_000),
CreateThread(512_000),
CreateThread(1_024_000),
CreateThread(2_048_000)
};
foreach (var thread in threads) thread.Start();
foreach (var thread in threads) thread.Join();
Console.ReadKey();
}
private Thread CreateControlThread()
=> new Thread(() => WriteMaximumStackSize(0));
private static Thread CreateThread(int maximumStackSizeInBytes)
=> new Thread(() => WriteMaximumStackSize(maximumStackSizeInBytes), maximumStackSizeInBytes);
private static void WriteMaximumStackSize(int expected)
{
GetCurrentThreadStackLimits(out uint low, out uint high);
if (expected > 0)
{
Console.WriteLine("Expected maximum stack size in bytes: " + expected.ToString("n0") + "; Actual: " + (high - low).ToString("n0"));
}
else
{
Console.WriteLine("Default maximum stack size in bytes: " + (high - low).ToString("n0"));
}
}
[DllImport("kernel32.dll")]
private static extern void GetCurrentThreadStackLimits(out uint lowLimit, out uint highLimit);
}