C# garbage collector cross reference

2019-07-18 10:44发布

问题:

Will garbage collector free resources for cross referenced object/class, which is no longer referenced from main program. For example -

class class1
{
    class2 m_RefClass2;
}
class class2
{
    class1 m_RefClass1;
}

class class3
{
    public class3()
    {
        class1 obj1 = new class1();
        class2 obj2 = new class2();
        obj1.m_RefClass2 = obj2;
        obj2.m_RefClass1 = obj1;
    }
}

回答1:

Yes. The .NET garbage collector is not simply counting references (in which case such an arrangement would cause both classes to keep each other alive). Any object that is not "rooted" (meaning that there is no reference path to the object from a GC root object) is eligible for collection.