gpt4 book ai didi

c# - 计时器、事件和垃圾收集 : am I missing something?

转载 作者:可可西里 更新时间:2023-11-01 07:44:52 24 4
gpt4 key购买 nike

考虑以下代码:

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:这当然不是一个真正的程序,我只是想向某人证明一个观点......但我的证明没有用;)

最佳答案

OK,我想我知道发生了什么......我用Reflector查看了Timer类的代码,在Enabled<的setter中发现了如下指令属性:

this.timerRoot = GCHandle.Alloc(this);

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

关于c# - 计时器、事件和垃圾收集 : am I missing something?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2311027/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com