我试图更好地掌握.NET线程模型。 我已经多次听说和阅读过(最近是在观看此视频时:AppFabric.tv - Threading with Jeff Richter),.NET线程至少占用1MB内存(因为它们为其堆栈设置了1MB)。 现在,我尝试编写一些代码来证明这一点,但结果却像下面这样:
297 threads are using 42MB of memory
298 threads are using 43MB of memory
299 threads are using 40MB of memory
300 threads are using 40MB of memory
因此,这些线程似乎没有使用每个1MB的内存。
我已尽力复制上述视频中5分钟演示的程序,但似乎无法得到相同的结果,也不明白原因。由于内存消耗有时似乎在下降,我猜测线程必须正在退出或被放置在某个后台队列中?或者我没有正确地测量内存?
用于获得上述结果的程序如下:
class Program
{
static void Main(string[] args)
{
ManualResetEvent manualReset = new ManualResetEvent(false);
int createdThreads = 0;
try
{
while (true)
{
Thread t = new Thread(WaitOneEvent);
t.Start(manualReset);
createdThreads++;
Console.WriteLine("{0} threads are using {1}MB of memory", createdThreads, System.Diagnostics.Process.GetCurrentProcess().PrivateMemorySize64 / (1024 * 1024));
}
}
catch (OutOfMemoryException)
{
Console.WriteLine("Out of memory at {0} threads", createdThreads);
System.Diagnostics.Debugger.Break();
manualReset.Set();
}
}
private static void WaitOneEvent(object eventObject) {
((ManualResetEvent)eventObject).WaitOne();
}
}
非常感谢您的关注和支持,期待能为您提供帮助。