Garbage Collector in .NET

Go To


How does the garbage collector know the objects and variables are out of scope so they can be collected by garbage collector?

2012-04-04 05:55
by Gunner
Have you looked at MSDN? - Gary.S 2012-04-04 05:59


In short: Every application has a set of roots. Roots identify storage locations, which refer to objects on the managed heap or to objects that are set to null.

When the garbage collector starts running, it makes the assumption that all objects in the heap are garbage.

The garbage collector starts walking the roots and building a graph of all objects reachable from the roots.

All objects not reachable are removed (memory is freed)

This is taken from - good article about the garbage collection. The "interesting" part for you is "The Garbage Collection Algorithm". It is not a very long section

2012-04-04 06:07
by Casper Thule Hansen
Thanks @Casper Hanse - Gunner 2012-04-04 06:27
You're welcome : - Casper Thule Hansen 2012-04-04 06:38


No discussion of garbage collection in .NET would be complete without referring to Raymond Chen's excellent series of blog posts:

Here's a quote from the first article in the series:

When you ask somebody what garbage collection is, the answer you get is probably going to be something along the lines of "Garbage collection is when the operating environment automatically reclaims memory that is no longer being used by the program. It does this by tracing memory starting from roots to identify which objects are accessible."

This description confuses the mechanism with the goal. It's like saying the job of a firefighter is "driving a red truck and spraying water." That's a description of what a firefighter does, but it misses the point of the job (namely, putting out fires and, more generally, fire safety).

And here are a few interesting points that he demonstrates:

A correctly-written program cannot assume that finalizers will ever run.


An object in a block of code can become eligible for collection during execution of a function it called.


A parameter to a method can become eligible for collection while the method is still executing.


A weird real-world analogy: The garbage collector can collect your diving board as soon as the diver touches it for the last time—even if the diver is still in the air!

and, most succinctly:

Don't think of GC as tracing roots. Think of GC as removing things you aren't using any more.

2012-04-04 19:33
by Daniel Pryden


Please go through As it says

The garbage collector checks to see if there are any objects in the heap that are no longer being used by the application. If such objects exist, then the memory used by these objects can be reclaimed.

2012-04-04 05:59
by Rauf
-1: How is this answering the question - leppie 2012-04-04 06:01
@leppie See the question comment by Gray. S - Rauf 2012-04-04 06:02
I dont see any mention of stack crawling, which the most basic 'answer' here - leppie 2012-04-04 06:04