I have simple question about .net garbage collection. In the following code I create a listener class instance in the constructor of the child object. My question is does the listener class get collected by the garbage collection before the child or main object since there is no direct reference to it anywhere?
class MainObject
{
public void DoSomething()
{
}
}
delegate void someEventHandler();
class ChildObject
{
public event someEventHandler SomeEvent;
MainObject main;
public ChildObject(MainObject main)
{
this.main = main;
new Listener(this, main);
}
}
class Listener
{
MainObject main;
public Listener(ChildObject child, MainObject main)
{
this.main = main;
child.SomeEvent += new someEventHandler(child_SomeEvent);
}
void child_SomeEvent()
{
main.DoSomething();
}
}
There is a reference to it, in the invocation list
child.SomeEvent.Dangling event handlers are the number one cause for memory leaks in .NET applications.
It will be collected once the
childobject is collected, but if you want it to be collected before hand you need to remove it from the invocation list (by using the-=operator).