简体   繁体   中英

Garbage Collection, .NET, C#

I have three objects A, B and C. C is the child of both A and B. C has reference to A and B. A and B has reference to C. I understand that when the reference to C from both A and B gets deleted, C becomes garbage and will be collected by GC.

  1. Is my understanding correct?
  2. Should I set the Reference to A and B in C to NULL?
  3. If Yes, What is the benefit?

public class A { public C Cr { get; set; } }
public class B { public C Cr { get; set; } }
public class C 

{
    public A Ar { get; set; }
    public B Br { get; set; }

}
class Program
{
    static void Main(string[] args)
    {
        var oa = new A();
        var ob = new B();
        var oc = new C();

        oc.Ar = oa;
        oc.Br = ob;
        oa.Cr = oc;
        ob.Cr = oc;

        // Some operation

        oa.Cr = null;
        ob.Cr = null;

        //is the following code required?
        // if yes, what is the benefit?

        oc.Ar = null;
        oc.Br = null;

    }

Thanks

Ram

If there are no live references to C, then it becomes eligible for garbage collection. That doesn't mean it will be garbage collected straight away.

There's no need for you to set references to null within an object if that object is about to become eligible for garbage collection.

Note that if there are no "root" references to A, B or C, they will all be eligible for garbage collection, even if they continue to have references to each other.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM