Let’s say I have a class A which can fire an event called X. Now I have a class B and in a method I get an instance to A and bind the event to a handler in B:
public void BindEvent(A a)
{
a.X += AEventHandler;
}
I have three questions about this.
-
Is it true that when I now set the reference to the B instance to null, it won’t be garbage collected since the garbage collector thinks it’s still in use (thus keeping a useless and potentially interfering copy of B in memory).
-
What about when I have another object c (of class C) in which I have a reference to A called a (“this.a = new A()”). Then I call “b.BindEvent(this.a)”, and in c I set the reference to a to null (“this.a = null”). Will this keep the copy of A in memory because it’s referenced through the event in b?
-
If either or both are true of the above, how can I best circumvent these issues? If I have a whole list of event handlers (say 10 lines like “a.SomeEvent += SomeMethod”) should I clean them all up again (“a.SomeEvent -= SomeMethod”). At which time or place in the code should I do these things?
Well it’s gotten a bit fuzzy but I’m not sure how to explain in a better way. Please leave a comment if I need to explain something more detailed.
so:
Ais the publisher andBis the subscriber?first bullet: if
Bis the instance withAEventHandler– then it is still in use, so no, it won’t get collected unless theainstance is unreachable.second bullet: huh? (will read again…) If the
AandBinstances are both unreachable, they will be garbage collected; the event doesn’t matter. IfAis reachable, thenBwill stay alive. However, the event subscription never keepsAalive; it is one way…Acan keepBalive, butBdoesn’t keepAalive. Does that cover it?third bullet: in most cases, the two things have similar life expentency, so it isn’t an issue. It only becomes an issue if the thing publishing the event lives a lot longer than the things with the handlers. In which case, you simply need to religiously clean up after yourself – for example:
a.X -= AEventHandler. In particular,staticevents are evil for this reason.