定时器,事件和垃圾收集:我错过了什么?
请考虑以下代码:
class TestTimerGC : Form { public TestTimerGC() { Button btnGC = new Button(); btnGC.Text = "GC"; btnGC.Click += (sender, e) => GC.Collect(); this.Controls.Add(btnGC); System.Windows.Forms.Timer tmr = new System.Windows.Forms.Timer(); tmr.Interval = 1000; tmr.Tick += (sender, e) => this.Text = DateTime.Now.ToString(); tmr.Start(); } }
如果我没有弄错,在tmr
变量超出范围之后, Timer
不会在任何地方被引用,因此它应该有资格进行垃圾回收。 但是当我点击GC按钮时,计时器继续运行,所以我猜它没有被收集……
有没有人对此有解释?
PS:当然,这不是一个真正的程序,我只是想向别人certificate一点…但我的证据不起作用;)
好吧,我想我知道发生了什么……我用Reflector查看了Timer
类的代码,并在Enabled
属性的setter中找到了以下指令:
this.timerRoot = GCHandle.Alloc(this);
因此,当它启动时,计时器为自己分配一个GCHandle
,这阻止了GC的收集……