开发者

Garbage Collection, .NET, C#

开发者 https://www.devze.com 2023-02-25 09:28 出处:网络
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 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 { ge开发者_开发知识库t; 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号