How to keep a weak link to an object?

(FYI: this question is half toric. This is not what I definitely plan to do).

I would like to be able to store a link to all the objects that I create. Maybe like this:

class Foo { private static List<Foo> AllMyFoos = new List<Foo>(); public Foo() { AllMyFoos.Add(this); } } 

The problem is that now none of my Foos can fall out of focus and collect trash. Is there a way to keep the link without interfering with the garbage collector?

Ideally, I'm just a list of Foos that are still in use, and not all Foos that have ever been used.

+4
source share
2 answers

Use WeakReference - it does exactly what it should. Be careful when working with it - you need to check if the link saves all the time when you play it .

Tutorial .


 Foo foo = AllMyFoos[index].Target as Foo; if (foo == null) { // Object was reclaimed, so we can't use it. } else { // foo is valid. My theoretical curiosity can be satisfied } 

Warning Just because the object has not yet been garbage collected, this does not mean that someone has not called Dispose on it, or in any other way put it in a state, it is not ready to be used again.

+6
source

There is a special thing that is named that way - WeakReference

+1
source

All Articles