static class Program {
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main() {
B b = new B(new A());
Console.Read();
b = null;//运行此代码后b之前引用的对象被释放
Thread.Sleep(3500 * 1000);
} public class A {
private event EventHandler m_testEvent;
public event EventHandler TestEvent {
add {
this.m_testEvent += value;
}
remove {
this.m_testEvent -= value;
}
}
} public class B {
public B(A a) {
this.m_a = a;
this.m_a.TestEvent += delegate(Object sender,EventArgs e) {
this.process();
};
this.m_a.TestEvent += new EventHandler(m_a_TestEvent);
} private A m_a; void m_a_TestEvent(object sender,EventArgs e) {
this.process();
} private void process() {
for(int i = 0;i >= 0;i++) {
}
}
}
}
类A和类B是否构成了循环引用?
为什么运行完Main方法的第三行后,b之前引用的对象图会被释放掉?
望高人解答 :D
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main() {
B b = new B(new A());
Console.Read();
b = null;//运行此代码后b之前引用的对象被释放
Thread.Sleep(3500 * 1000);
} public class A {
private event EventHandler m_testEvent;
public event EventHandler TestEvent {
add {
this.m_testEvent += value;
}
remove {
this.m_testEvent -= value;
}
}
} public class B {
public B(A a) {
this.m_a = a;
this.m_a.TestEvent += delegate(Object sender,EventArgs e) {
this.process();
};
this.m_a.TestEvent += new EventHandler(m_a_TestEvent);
} private A m_a; void m_a_TestEvent(object sender,EventArgs e) {
this.process();
} private void process() {
for(int i = 0;i >= 0;i++) {
}
}
}
}
类A和类B是否构成了循环引用?
为什么运行完Main方法的第三行后,b之前引用的对象图会被释放掉?
望高人解答 :D
简单的讲:A对象是B对象的成员变量,在B的构造函数中又注册了A对象的事件;
这样似乎造成了A、B的循环引用,但垃圾回收还是将B对象回收了。
不清楚为什么B对象会被回收,有兴趣的一起讨论讨论 :D