Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Garbage Collection Active Roots

I'm reading about the C# garbage collector, and how the CLR builds object graphs. The chapter references different roots that could be active for the object:

• References to global objects (though these are not allowed in C#, CIL code does permit allocation of global objects)
• References to any static objects/static fields
• References to local objects within an application’s code base
• References to object parameters passed into a method
• References to objects waiting to be finalized (described later in this chapter)
• Any CPU register that references an object

I was wondering if someone could give examples of these roots in code?

Thanks

like image 830
Ben Gale Avatar asked Dec 01 '11 16:12

Ben Gale


1 Answers

Assume you run the following program:

class Program
{
    static Class1 foo = new Class1();

    static void Main(string[] args)
    {
        Class2 bar = new Class2();

        Class3 baz = new Class3();
        baz = null;

        Debugger.Break();

        bar.Run();
    }
}

When the program breaks into the debugger, there are 3+ objects that are not eligible for garbage collection because of the following references:

  • a Class1 object referenced by the static field foo
  • a string[] object referenced by the parameter args
  • zero or more string objects referenced by the string[] object referenced by args
  • a Class2 object referenced by the local variable bar

The Class3 object is eligible for garbage collection and may already have been collected or be waiting to be finalized.

References to global objects are not allowed in C#. References in CPU registers are an implementation detail of the VM.

like image 103
dtb Avatar answered Sep 21 '22 21:09

dtb