计时器、事件和垃圾收集:我错过了什么吗? [英] Timer, event and garbage collection : am I missing something?
问题描述
考虑以下代码:
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按钮时,计时器继续运行,所以我猜它没有被收集......
If I'm not mistaken, after the tmr
variable goes out of scope, the Timer
isn't referenced anywhere, so it should be eligible for garbage collection. But when I click the GC button, the timer continues to run, so I guess it wasn't collected...
有没有人解释一下?
PS:这当然不是一个真正的程序,我只是想向某人证明一个观点......但我的证明没有奏效;)
推荐答案
好吧,我想我知道发生了什么......我用 Reflector 查看了 Timer
类的代码,然后我在 Enabled
属性的 setter 中找到以下指令:
OK, I think I know what's going on... I looked at the code of the Timer
class with Reflector, and I found the following instruction in the setter of the Enabled
property :
this.timerRoot = GCHandle.Alloc(this);
所以,当它启动时,定时器为自己分配一个GCHandle
,这阻止了它被GC收集......
So, when it is started, the timer allocates a GCHandle
for itself, which prevents its collection by the GC...
这篇关于计时器、事件和垃圾收集:我错过了什么吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!