views:

228

answers:

2

What happens to the WeakReference when the target object referenced by WeakReference.Target has been garbage collected? Does the WeakRerence stay alive and keeps existing? The reason why I am asking is that I have a list of WeakReferences stored in a List. During runtime new WeakReferences constantly are getting added to that list. Now when the target object dies, do I have to cleanup the abandoned WeakReference myself? If so, is there a clever trick how I could do this? Can I get notified when a WeakReference becomes abandoned? Or do I have to introduce a timer that frequently loops through that list, to see if any WeakReference instances can be removed from that list.

+3  A: 

Since you have a strong reference to the WeakReference object, it will not get GC'ed. This is also by design, because it was intended that you can still use the WeakReference to find out that the target has been GC'ed.

So yes, you'll have to go the timer way.

Added: You might also take a look at Garbage Collection Notifications.

Vilx-
+1, but I'd caution against the GC notifications, as they disable some of the newer (nice) features of the GC.
sixlettervariables
+7  A: 

This is a common problem with weak references. The reference itself remains alive because it has normal pointers to it. As you suggest, you need to do some "manual garbage collection" from time to time. Note that you can probably clean up the stubs on your way when you are traversing the list for another reason. Depending the use pattern for the list, this "on the side" garbage collection may even be enough.

Do not "frequently" loop through the list for the sole purpose of cleaning it up! Each dead stub only wastes a couple of words of memory. If the list is not used often the computational cost of cleaning it often is not justified, and if it is used frequently it will clean itself up as suggested above.

It's in another garbage-collected system altogether, but the problems are so similar that you may be interested in this article if you can get it.

Pascal Cuoq