定时器,事件和垃圾收集:我失去了一些东西? [英] Timer, event and garbage collection : am I missing something?

查看:176
本文介绍了定时器,事件和垃圾收集:我失去了一些东西?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下code:

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 变量超出范围,定时器不任何地方引用,所以它应该是符合垃圾收集。但是,当我点击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...

有没有人有一个解释是什么?

Does anyone have an explanation for that ?

PS:这当然不是一个真正的程序,我只是想证明这一点的人......但我证明没有工作;)

推荐答案

好了,我想我知道这是怎么回事......我看了看计时器的code 类反射器,我发现下面的指令在已启用 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 的本身,$ P $由GC pvents其收藏...

So, when it is started, the timer allocates a GCHandle for itself, which prevents its collection by the GC...

这篇关于定时器,事件和垃圾收集:我失去了一些东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆