If you enjoy this article, make sure to check the 2nd edition of Pro .NET Memory Management for more insights on the .NET Garbage Collector internals! After a long (way too long) break, it’s time to resume our journey towards building a .NET garbage collector in C#. In the previous parts, we saw how to implement the minimal set of GC APIs to allow a simple application to run, and how to lay out the objects in memory to make the heap walkable. We then learned how to find the references of a given managed object. If you need a refresher, don’t hesitate to jump back to those past articles: Part 1: Introduction and setting up the project Part 2: Implementing a minimal GC Part 3: Using the DAC to inspect the managed objects Part 4: Walking the managed heap Part 5: Decoding the GCDesc to find the references of a managed object If you don’t have time to read everything, I would recommend focusing on part 4 which explains the layout of the heap. Now we have all the pieces of the puzzle to start implementing the mark phase of our garbage collection. The goal of the mark phase is to find all the objects that are currently reachable by user code, to deduce which ones aren’t reachable anymore and can be freed. Marking Marking starts from the roots. That is: references that the GC treats as unconditionally live at the beginning of a collection. The roots can be sorted into three buckets: the local variables and thread-static storage, the GC handles, and the finalization queue. You might also think of static fields, however in practice the static variables are kept alive by GC handles. While the GC is responsible for the last two buckets, the first one is handled directly by the runtime. The IGCToCLR interface exposes a GcScanRoots method that takes a callback, which will be called for every local variable. In addition to the callback, the GcScanRoots method takes 3 arguments: condemned and max_gen which are only used for some corner cases with server GC, and so are largely incon...
First seen: 2026-01-31 22:42
Last seen: 2026-02-01 04:42