日期:2014-05-17  浏览次数:21002 次

《你不常用的c#之五》:Thread与ThreadPool的内存之战

Thread与ThreadPool使用的时候在内存里对象是如何分布的呢?
今天我们就从内存堆的角度分析下两者。
先上小白鼠代码:

<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->static?void?Main(string[]?args)
????????{
????????????
for?(int?i?=?0;?i?<?30;?i++)
????????????{
????????????????Thread?t?
=?new?Thread(new?ThreadStart(ThreadProc));
????????????????t.Name?
=?"Overred_"?+?i;
????????????????t.Start();
????????????}
????????????Console.Read();
????????}
????????
static?void?ThreadProc()
????????{
????????????
try
????????????{
????????????????
for?(int?i?=?0;?i?<?10;?i++)
????????????????{
?????????????????????Console.WriteLine(
"{0}??Value:{1}",Thread.CurrentThread.Name,i);
????????????????}
???????????????
????????????}
????????????
catch?(Exception?ex)
????????????{
????????????????Console.WriteLine(ex.Message);
????????????}
????????}

以上代码非常简单,就是循环启动30个线程去执行同一个方法ThreadProc(),然后打印出结果。
现在提出问题1:当Main里的30个线程都把ThreadProc()方法执行完毕后,这些Threads是自动消亡还是被GC回收,还是变成DeadThread?
好,拿出我们的看家工具windbg,来debug一把。
首先启动我们的程序,然后打开windbg,然后F6,Attach我们的exe
1,加载mscorwks(.net 2.0或者以上)
<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->0:003>?.loadby?sos?mscorwks?