Search code examples
c#weak-references

In c# how to know if a weak referenced object is going to be garbage collected?


Suppose I have such code:

class Test
{
    WeakReference m_ref;

    public Test()
    {
        Test1();
        Test2();
    }

    void Test1()
    {
        m_ref = new WeakReference(new object());
    }

    void Test2()
    {
        // If I do the GC then the m_ref.Target is null
        // GC.Collect();
        Debug.Log(m_ref.Target);
    }
}

void TestFunc()
{
    new Test();
}

In this example I created a new object instance and set it to a WeakReference instance in Test1. If I understand correctly after exit the Test1 there would be nothing referenced to the object instance so this instance would be GC soon.

However, in the Test2 if GC is not performed I can still access the object instance via m_ref.Target.

Is there any way I could know that the m_ref.Target is invalid without manually perform the GC?


Solution

  • Nope, you can't. By design, WeakReference is tightly coupled to the garbage collector. Even the documentation mentions it:

    Gets an indication whether the object referenced by the current WeakReference object has been garbage collected.

    As far as I know, there's no way in C# to know whether there's still alive references to a given object, except maybe manually browsing the whole reference tree (and pretty much reimplementing the GC yourself).