using System.Threading;
Thread T = new Thread(threadDelegate, stackSizeInBytes);
T.Start();
您可以使用 System。诊断。属性来计算所使用的帧的数量,并在达到帧限制时引发自己的异常。
或者,可以计算剩余堆栈的大小,并在堆栈低于阈值时抛出自己的异常:-
class Program
{
static int n;
static int topOfStack;
const int stackSize = 1000000; // Default?
// The func is 76 bytes, but we need space to unwind the exception.
const int spaceRequired = 18*1024;
unsafe static void Main(string[] args)
{
int var;
topOfStack = (int)&var;
n=0;
recurse();
}
unsafe static void recurse()
{
int remaining;
remaining = stackSize - (topOfStack - (int)&remaining);
if (remaining < spaceRequired)
throw new Exception("Cheese");
n++;
recurse();
}
}