The Garbage Collector concept is about automatic memory management: the runtime keeps track of objects your program creates and reclaims memory from those that can no longer be reached. Core ideas 1. Reachability, not reference counting .NET does not count references. An object is "alive" if it can be reached from a root — static fields, local variables on any thread's stack, CPU registers or GC handles. Circular references between unreachable objects are collected without problems. 2. Tracing collection: mark and compact The GC pauses managed threads (or runs partly in the background), marks all reachable objects, frees the rest and compacts survivors to avoid fragmentation. 3. Generational hypothesis Most objects die young. So the heap is divided into Gen 0, Gen 1 and Gen 2. Collecting only Gen 0 (cheap and frequent) reclaims most garbage; long-lived objects are promoted to Gen 2 and checked rarely. Large objects (85 KB and above) live on the Large Object Heap, and pinned objects can use the Pinned Object Heap. 4. Non-deterministic timing You cannot predict exactly when an object will be collected. That is why deterministic cleanup of resources uses IDisposable, not the GC. 5. Finalization Objects with finalizers are put on a finalization queue when found unreachable; a finalizer thread runs them, and memory is reclaimed in a later collection. This delays cleanup, so finalizers should only exist for unmanaged handles, with Dispose calling GC.SuppressFinalize(this). 6. Configurable modes Workstation vs Server GC, concurrent/background GC, and newer adaptive behaviour (DATAS) that adjusts heap counts for container workloads. Settings can be changed in runtimeconfig.json or environment variables. Why developers still need to care - Memory leaks happen in managed code when objects stay reachable unintentionally: static lists, caches without limits, event subscriptions, long-lived closures and timers. - High allocation rates cause frequent collections and latency spikes; reduce them with pooling (ArrayPool<T>), Span<T>, avoiding unnecessary LINQ and string concatenation in hot paths. - Use "using" for streams, connections and other disposables. Weak references (WeakReference<T>) allow referencing an object without keeping it alive — useful for some caches.
Ravindra Wadile · · 0 likes