Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep a weak reference to an object?

(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.

like image 420
Buh Buh Avatar asked Oct 11 '11 14:10

Buh Buh


1 Answers

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.

like image 83
Matěj Zábský Avatar answered Sep 24 '22 05:09

Matěj Zábský