MSDN Documentation

.NET Memory Management

Introduction

.NET provides an automatic memory management system that relieves developers from manual allocation and deallocation of memory. The core component is the Garbage Collector (GC), which runs periodically to reclaim memory occupied by objects that are no longer reachable.

Garbage Collection

The GC in .NET is a generational, mark‑and‑sweep collector. It categorizes objects into three generations (0, 1, 2) based on their lifetime. Younger generations are collected more frequently.

Managed Heap

The managed heap is where all reference‑type objects live. It is divided into segments that hold generations. Allocation is fast because it simply advances a pointer, and deallocation occurs during GC cycles.

Large Object Heap (LOH)

Objects larger than 85,000 bytes are allocated on the LOH, which is not compacted by default. Starting with .NET 5, LOH compaction can be enabled.

// Enable LOH compaction for the next collection
GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
GC.Collect();

Finalization & IDisposable

Finalizers allow an object to release unmanaged resources when the GC collects it, but they are nondeterministic. Implement IDisposable and use the using statement for deterministic cleanup.

public sealed class SafeHandleWrapper : IDisposable{
    private SafeHandle _handle;
    private bool _disposed;
    public SafeHandleWrapper(SafeHandle handle){
        _handle = handle;
    }
    public void Dispose(){
        Dispose(true);
        GC.SuppressFinalize(this);
    }
    private void Dispose(bool disposing){
        if(_disposed) return;
        if(disposing){
            // free managed resources
        }
        // free unmanaged resources
        _handle?.Dispose();
        _disposed = true;
    }
    ~SafeHandleWrapper(){
        Dispose(false);
    }
}

Usage:

using(var resource = new SafeHandleWrapper(handle)){
    // work with resource
}

Performance Tips