The .NET Garbage Collector (GC) is the part of the runtime that manages memory for managed objects. It decides when objects are no longer needed and reclaims their memory, removing whole classes of bugs such as double frees and dangling pointers. What triggers a collection: - Gen 0's allocation budget is exhausted (the most common trigger). - The system reports low memory. - GC.Collect is called explicitly (rarely a good idea). The mark, sweep and compact cycle: 1. Mark: starting from roots (statics, stack variables, registers, GC handles), find every reachable object. 2. Sweep: memory of unreachable objects becomes free. 3. Compact: move surviving objects together and update references, so new allocations stay fast and contiguous. Generational model: - Gen 0 — newly allocated objects; most die here. - Gen 1 — survived one collection; acts as a buffer. - Gen 2 — long-lived objects; full collections are more expensive. - LOH (85 KB and larger objects) and POH (pinned object heap, .NET 5+) are special areas collected with Gen 2. Performance features: - Server GC (default for ASP.NET Core) uses multiple heaps and threads for throughput. - Background GC lets Gen 2 collections run while application threads continue. - GC settings such as GCHeapHardLimit or DOTNET_GCHeapAffinitizeMask help in containers. Finalization and IDisposable: - Objects with finalizers are put on a finalization queue and survive an extra GC, so avoid finalizers unless you directly own unmanaged handles (prefer SafeHandle). - Use the Dispose pattern and "using" statements to release unmanaged resources promptly; GC.SuppressFinalize in Dispose avoids unnecessary finalization. Writing GC-friendly code: reduce allocations in hot paths (Span<T>, ArrayPool<T>, StringBuilder, avoiding LINQ in tight loops), avoid holding references longer than needed, and watch for leaks from static collections and event subscriptions. Measure with dotnet-counters (GC heap size, % time in GC, Gen 2 count) before optimising.
Ravindra Wadile · · 0 likes