定时器,事件和垃圾收集:我错过了什么?

Tho*_*que 15 .net c# garbage-collection timer

请考虑以下代码:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我没有弄错,在tmr变量超出范围之后,Timer就不会在任何地方引用它,因此它应该有资格进行垃圾收集.但是当我点击GC按钮时,计时器继续运行,所以我猜它没有被收集......

有没有人对此有解释?

PS:当然,这不是一个真正的程序,我只是想向别人证明一点...但我的证据不起作用;)

Tho*_*que 21

好吧,我想我知道发生了什么......我Timer用Reflector 查看了类的代码,并在Enabled属性的setter中找到了以下指令:

this.timerRoot = GCHandle.Alloc(this);
Run Code Online (Sandbox Code Playgroud)

因此,当它启动时,计时器GCHandle为自己分配一个,这阻止了它由GC收集......