C# / .NET Compendium PLEN
.NET / C# / Memory and threads

Memory management in .NET - the Garbage Collector

The generational Garbage Collector - the fundamental architecture

The .NET GC is based on an observation: most objects live briefly (local variables, temporary DTOs), and a minority live long (Singletons, static caches). The GC divides the heap into generations, optimising for this observation.

Gen 0 (young objects)     → Gen 1 (survived one GC)  → Gen 2 (long-lived)
Collected VERY often    Collected less often            Collected least often
var order = new Order(); // trafia do Gen 0

Every newly created reference object goes into Gen 0. When Gen 0 fills up, the GC performs a Gen 0 collection - it checks which objects are still "alive" (have active references) and removes the rest. Objects that survived the collection (because they are still in use) are promoted to Gen 1.

Why this is efficient: a Gen 0 collection is very fast (a small amount of memory to scan, most short-lived objects are already "dead" anyway). If the GC had to always scan the whole heap, it would be drastically slower - hence the division into generations, where Gen 2 rarely has to be scanned (because little changes there).

Mark-and-Sweep - how a collection actually works

1. MARK (oznaczanie) - GC przechodzi od "korzeni" (root - zmienne lokalne na stosie, statyczne pola)
   and marks ALL the objects reachable through references as "alive"

2. SWEEP (collection) - everything UNMARKED (unreachable) is considered "garbage" and its memory is freed

3. COMPACT (compaction) - the live objects are MOVED to merge the free memory into one contiguous block
   (eliminates fragmentation)

This explains why circular references are NOT a problem in .NET (unlike simple reference counting, e.g. in old COM) - if two objects reference each other, but no root leads to them, the GC will consider them unreachable anyway and free them.

LOH (Large Object Heap) - special treatment of large objects

var bigArray = new byte[100_000]; // > 85,000 bytes → goes to the LOH, NOT to Gen 0!

Objects larger than ~85 KB go to a separate part of the heap (the Large Object Heap), which is rarely compacted (moving large blocks of memory is expensive) - this can lead to LOH fragmentation when large arrays are frequently created/freed, which is a common source of performance problems in applications processing large amounts of data (e.g. large buffers when processing files).

.NET Framework vs .NET Core/.NET 5+ - differences in the GC

.NET Framework .NET Core / .NET 5+
Default GC Workstation GC (single thread) Server GC (multithreaded, the default in ASP.NET Core)
Configurability Limited More granular (runtimeconfig.json, env variables)
Performance for servers Weaker under heavy load Much better (Server GC scales with the number of CPU cores)
// runtimeconfig.json - konfiguracja GC w .NET Core/.NET 5+
{
  "configProperties": {
    "System.GC.Server": true,        // Server GC - multithreaded, better for high throughput
    "System.GC.Concurrent": true      // Background GC - part of the work in the background, fewer pauses
  }
}

Server GC creates a separate GC thread per CPU core and a separate heap per thread - it scales much better on multi-core servers (typical for ASP.NET Core in production), at the cost of higher memory use compared with Workstation GC (better for desktop applications like WPF, where UI responsiveness matters, not maximum throughput).

IDisposable/using - UNMANAGED resources that the GC doesn't see

This is a key distinction - the GC manages managed memory (.NET objects), but doesn't know about unmanaged resources (file handles, network connections, operating system handles):

public class FileProcessor : IDisposable
{
    private readonly FileStream _stream; // an UNMANAGED resource - an operating system handle

    public FileProcessor(string path) => _stream = File.OpenRead(path);

    public void Dispose() => _stream?.Dispose(); // you MUST release it MANUALLY, the GC won't do it for you
}
using (var processor = new FileProcessor("data.txt"))
{
    // ...
} // Dispose() is called AUTOMATICALLY at the end of the block, even if an exception is thrown

Why this matters: without using/Dispose(), the file handle stays open, even though the FileProcessor object itself (managed memory) may long since have been collected by the GC - this leads to exhaustion of operating system resources (e.g. "too many open files"), completely regardless of how much "free RAM" you have.

Finalizers - the "last line of defence", but expensive

public class FileProcessor : IDisposable
{
    private readonly FileStream _stream;

    ~FileProcessor() // a finalizer - called by the GC if Dispose() was NOT called
    {
        _stream?.Dispose();
    }

    public void Dispose()
    {
        _stream?.Dispose();
        GC.SuppressFinalize(this); // "you don't need to finalize me, I've ALREADY cleaned up manually"
    }
}

Objects with a finalizer require two GC passes to be fully freed (first the finalizer is executed, the object goes onto a special queue, and only the next collection actually frees the memory) - hence GC.SuppressFinalize(this) in Dispose() is an important optimisation, telling the GC that the finalizer is unnecessary, because the resources have already been released manually.

Summary - practical consequences for everyday code

The .NET GC divides the heap into generations (Gen 0/1/2), optimising for the observation that most objects live briefly - a Gen 0 collection is frequent and fast, Gen 2 rare and expensive. Server GC (the default in ASP.NET Core) scales multithreaded with the number of CPU cores, at the cost of higher memory use. The key practical rule: the GC manages only .NET memory - unmanaged resources (files, sockets, database connections) require an explicit Dispose()/using, regardless of when the GC frees the "container" object of those resources itself.

Buy me a coffee