C # Garbage Collection Active Roots

I read about the C # garbage collector and how the CLR builds graphical objects. The chapter describes the different roots that can be active for an object:

• References to global objects (although they are not allowed in C #, CIL code allows the selection of global objects)
• Links to any static objects / static fields
• Links to local objects within the application code base
• References to the passed parameters of the object to the method • References to objects awaiting completion (described later in this chapter)
• Any CPU register that is referenced by an object

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

thanks

+7
source share
2 answers

Suppose 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 a program breaks down into a debugger, there are 3+ objects that cannot be selected for garbage collection due to the following links:

  • a Class1 object referenced by the static field foo
  • a string[] object referenced by the args parameter
  • 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 has the right to collect garbage and may already be collected or wait for completion.

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

+7
source
 class Test { static object ImARoot = new object(); //static objects/static fields void foo(object paramRoot) // parameters I'm a root to but only when in foo { object ImARoot2 = new object(); //local objects but only when I'm in foo. //I'm a root after foo ends but only because GC.SuppressFinalize is not called called (typically in Dispose) SomethingWithAFinalizer finalizedRoot = new SomethingWithAFinalizer (); } } 

If you ever want to find out what the object is currently attached to, you can use SOS (in Visual Studio 2005 or later or in WinDbg) and use the command! gcroot.

+1
source

All Articles