【发布时间】:2017-12-09 14:30:59
【问题描述】:
我对事件处理程序如何影响垃圾回收操作感到完全困惑。
比如为什么对象a1没有被垃圾回收(a1的析构函数没有调用):
即使在取消订阅 timeChange eventHandler 之后,垃圾收集器也不会调用析构函数。
最好的问候。
public class B
{
private void button1_Click(object sender, EventArgs e)
{
A a1 = new A();
a1.timeChange += A1_timeChange;
a1.Start();
a1 = null;
GC.Collect();
}
private void A1_timeChange(object sender, EventArgs e)
{
MessageBox.Show(((DateTime)sender).ToString() );
}
}
public class A
{
~A()
{
MessageBox.Show("A Collected");
}
public void Start()
{
if (timeChange != null)
{
Task.Factory.StartNew(() => {
while (true)
{
timeChange(DateTime.Now, null);
System.Threading.Thread.Sleep(3000);
}
});
}
}
public event EventHandler timeChange;
}
【问题讨论】:
-
任务通过
this.timeChange成员保持引用,this变为未定义将是灾难性的。 while (true) 循环确保它永远被引用。任意将事件设为静态,您现在会看到它被收集起来。
标签: c# .net winforms garbage-collection eventhandler