Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท .NET, Tools and Concepts

Garbage collection in .NET

Reference for the .NET garbage collector: generations 0 to 2, the large object heap, workstation and server GC, the GC class, weak references and tuning.

The garbage collector (GC) is the part of the .NET runtime that finds heap objects your program can no longer reach and reclaims their memory. You allocate with new; you never free. The GC works with generations: new objects start in generation 0, survivors move to generation 1 and then generation 2, because most objects die young and the GC can check the young ones cheaply and often.

The System.GC class lets you observe the collector (CollectionCount, GetGeneration, GetTotalMemory) and, rarely, steer it (Collect, AddMemoryPressure, TryStartNoGCRegion). The collector's mode is configured, not coded: see "Syntax" below.

C#
object o = new object();
int generation = GC.GetGeneration(o);   // 0 for a new object
GC.Collect();                           // diagnostic use only

Try it

C# Objects move up a generation each time they survive

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Weak references and finalization after a collection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

The System.GC class

Member Description
GC.Collect() / GC.Collect(int generation) Forces a collection of that generation and all younger ones. For tests and diagnostics, not production code.
GC.CollectionCount(int generation) Number of collections of that generation since the process started.
GC.GetGeneration(object) The generation an object is in now.
GC.GetTotalMemory(bool forceFullCollection) Approximate bytes in the managed heap.
GC.GetAllocatedBytesForCurrentThread() Bytes this thread has allocated. Good for allocation tests.
GC.GetGCMemoryInfo() Heap sizes, fragmentation, pause times of the last collection.
GC.KeepAlive(object) Keeps an object reachable up to this call.
GC.SuppressFinalize(object) Tells the GC not to run an object's finalizer (used in Dispose).
GC.AddMemoryPressure(long) / RemoveMemoryPressure Tells the GC about unmanaged memory a managed object owns.
GC.TryStartNoGCRegion(long) / EndNoGCRegion() Asks to run a block of code without any collection.
GC.MaxGeneration The highest generation number (2).

Generations and heaps

Area Contents When collected
Generation 0 New small objects Very often, in milliseconds or less
Generation 1 Survivors of gen 0, a buffer between 0 and 2 Often
Generation 2 Long-lived objects Rarely, and then the whole heap is examined
Large object heap (LOH) Objects of 85,000 bytes or more (they count as gen 2) With gen 2
Pinned object heap (POH) Arrays created with GC.AllocateArray(pinned: true) With gen 2

Workstation and server GC, concurrent GC

  • Workstation GC (default for desktop apps) uses one heap and is tuned for responsiveness. Server GC uses a heap and a GC thread per core for throughput on multi-core servers. ASP.NET Core apps normally run with server GC when more than one processor is available.
  • Concurrent / background GC lets gen 2 collections run mostly while your threads keep running, shortening pauses.
  • Set modes in the project file (<ServerGarbageCollector>, <ConcurrentGarbageCollection>, <TieredPGO>) or in runtimeconfig.json (System.GC.Server, System.GC.Concurrent, System.GC.ConserveMemory).
  • GCSettings.LatencyMode can be switched temporarily, for example to SustainedLowLatency.

Usage notes

  • Do not call GC.Collect() to "free memory". The collector knows better; forced collections promote objects too early and cost time. Tests that check for leaks are the main legitimate use.
  • A reachable object is never collected. Leaks in managed code are usually forgotten event subscriptions, static collections, caches without limits or captured closures, not missing frees.
  • Release builds can free objects earlier. The JIT treats a local as dead after its last use, so an object may be collected before the end of the method. Use GC.KeepAlive when you need an object to live to a specific point.
  • Finalizers delay cleanup. An object with a finalizer survives its first collection and needs another cycle. Prefer IDisposable and SafeHandle.
  • The LOH is expensive to collect and was historically not compacted. Avoid allocating many large short-lived arrays; use ArrayPool<T> to reuse them.
  • Allocation rate matters more than heap size. Generation 0 collections are cheap, but every allocation adds pressure, so avoid needless boxing, string concatenation in loops and closures in hot paths.
  • GC.Collect output counts differ between runs and machines. Examples that print generation numbers or counts are about the pattern, not the exact number of collections the runtime performs on its own.