(FYI: This question is half thoretical. It is not something which I am definatly planning on doing.)
I would like to be able to keep a reference 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 trouble with this is that now none of my Foos can ever drop out of focus and be garbage collected. Is there any way of keeping a referance without getting in the way of the garbage collector?
Ideally I just of a list of Foos that are still being used, not all Foos which have ever been used.
Use WeakReference - it does exactly what it is supposed to. Be careful while working with it - you have to check if the reference is still valid every time you dereference 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 hasn't yet been garbage collected doesn't mean someone hasn't called Dispose
on it, or in some other way put it into a state that it is not prepared to be used again.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With