I have a parent object that has a reference to a child object and additionally the parent has an event handler that listens to an event of the child object.
If all references to the parent object will be released, will the memory used through the parent and the child be freed through GC? (Assuming that no more references neither to the child nor to the parent exist).
class ParentClass {
ChildClass _childClass;
public ParentClass(ChildClass childClass) {
_childClass = childClass;
childClass.SomeEvent += ChildClass_SomeEvent;
}
void ChildClass_SomeEvent(object sender, SomeEventArgs e) {
}
}
Please note, I'm aware that GC does not react immediately. My question is not if the memory is freed immediatly after releasing the parent object. My question is, if the memory is released anyhow.
Update
For me it seems that the answer is a clear yes, GC is able to resolve this circular reference. But for all who read this post and have a similar question, take care to not leave event-registration open. It's only a special example in which the registration is no problem. In other cases, event-registrations may cause serious memory leaks.
A very good resource covering this question was provided by vilx: http://www.interact-sw.co.uk/iangblog/2004/07/07/circulareventrefs