我完全不明白事件处理程序如何影响垃圾回收操作。
例如,为什么对象a1没有被垃圾回收(a1的解构器没有调用):
即使取消订阅timeChange事件处理程序后,解构器也没有被垃圾回收器调用。
此致
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)
循环确保它永远保持引用。任意将事件设为静态,你现在会看到它被收集了。 - Hans Passant