Overview
The .NET Garbage Collector (GC) is a fully managed, generational, mark‑and‑sweep collector that automatically reclaims memory used by your applications. It runs concurrently with the managed threads and strives to keep pause times low while maximizing throughput.
The GC operates in three generations (0, 1, 2) and employs a large object heap (LOH) for objects >85 KB. It also supports background collection, server vs. workstation modes, and a variety of configuration options through runtimeconfig.json
or GCSettings
.
Generations
Objects start in Generation 0. If they survive a collection they are promoted to higher generations.
- Gen 0 – Short‑lived objects, collected frequently.
- Gen 1 – Medium‑lived objects, promotion after surviving Gen 0.
- Gen 2 – Long‑lived objects, collected less often.
- LOH – Large objects allocated directly in a separate heap.
+-----------------------+
| Managed Heap |
| +---+ +---+ +-------+ |
| |G0 | |G1 | | G2 | |
| +---+ +---+ +-------+ |
| +-------------------+ |
| | Large Object Heap | |
| +-------------------+ |
+-----------------------+
Configuration
Control GC behavior via runtimeconfig.json
or programmatically.
{
"runtimeOptions": {
"configProperties": {
"System.GC.Server": true,
"System.GC.RetainVM": false,
"System.GC.HeapCount": 4
}
}
}
Programmatic example:
using System;
using System.Runtime;
GCSettings.LatencyMode = GCLatencyMode.LowLatency;
// …run critical section…
GCSettings.LatencyMode = GCLatencyMode.Interactive;
Diagnostics & Monitoring
Use built‑in tools to monitor GC activity.
dotnet-counters
– Real‑time counters.dotnet-trace
– Event tracing of GC events.dotnet-gcdump
– Capture heap snapshots.- Performance Counters –
GCHeapSize
,Gen 0 Collections
, etc.
# Sample: dotnet-counters monitor
dotnet-counters monitor -p <pid> System.Runtime
FAQ
How do I force a collection?
Use GC.Collect()
. This is rarely needed and can degrade performance.
What is a background GC?
In workstation mode, Gen 2 collections run in the background while the app continues executing, reducing pause times.