I just came across a pretty simple situation where GC will fail to collect
unused object and this could be a potential framework design bug. If it's
not acknowledged as bug, lots of developers would be needed to write lots of
extra code assuming they remember this! This simple situation is like this:
Lets have only two object variables A1 and B1 holding instances of the class
A and class B respectively. Let B1 listens to an event raised by A1. Now if
I set B1 to null, I would expect it to get collected in next GC cycle. Well,
this does not happens. Infact it won't get collected UNLESS you also set
event source A1 to null! If A1 happens to be some long living object (such
as screen level or global app level object), anyone who listens to it would
also become a long living object. This happens essentially without your
knowledge because as far as you are concerned you do not have any variables
in your code holding B1 any longer. In fact it is not possible to retrieve
B1 by anyway once you set it to null. So for you as a developer reference is
GONE but for GC it isn't.
This is a real trouble maker. In so many situations we create many objects
listening to an event from some other object. These listener guys won't go
away until that event generator object goes away. The only .Net way to get
around this would be to implement IDisposible which will remove event
handlers and calling Dispose over the listners. This is the reason I want to
consider this behavior has a bug because it makes event handlers look as if
they are system resources which needs to be disposed. They are really not
and makes whole scene really ugly. I guess a core CLR fix might be required
to avoid references captured by delegates to get notices by GC.
In attachment you can find little C# and VB projects which demonstrate this
bug.
Regards,
Shital.
http://www.ShitalShah.com
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Certainly the game is rigged, but don't let that stop you from playing.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~