GC.Collect and WeakReference
A weak reference
A WeakReference points at an object without keeping it alive: the collector may free the object, and the reference then reports IsAlive == false and a null Target. It is the tool for a cache that should not stop the collector from freeing its entries.
var reference = Create();
Console.WriteLine($"alive {reference.IsAlive}");
GC.Collect();
Console.WriteLine($"after collect {reference.IsAlive}");
Console.WriteLine($"target {reference.Target ?? "collected"}");
static WeakReference Create()
{
var data = new byte[1000];
return new WeakReference(data);
}
dotnet run
alive True
after collect False
target collected
The array was alive while the method held it, and gone after the method returned and the collection ran: only the weak reference was left, and a weak reference does not count. This is a measured collection, not a guess: IsAlive reads the state the collector left behind.
The local that would not die
The same test written in one method gives a different answer, and the reason is worth knowing:
byte[]? strong = new byte[1000];
var weak = new WeakReference(strong);
GC.Collect();
Console.WriteLine($"held {weak.IsAlive}");
strong = null;
GC.Collect();
Console.WriteLine($"after null {weak.IsAlive}");
Console.WriteLine($"target {weak.Target?.GetType().Name ?? "collected"}");
dotnet run
held True
after null True
target Byte[]
The second line says the array survived its only reference being set to null. This is a Debug build, and a Debug build keeps a local alive until the end of its method so that a debugger can still show it; the JIT does not report the variable as dead after its last use. A Release build lets the collector take it earlier, which the lesson on Debug against Release measures, and the helper method of the first program sidesteps the question by letting the frame end.
Forcing a collection
GC.Collect(n) runs a collection of generation n and every younger one, and GC.Collect() means a full collection of generation 2. The counters show what each call did:
Console.WriteLine($"before {GC.CollectionCount(0)} {GC.CollectionCount(1)} {GC.CollectionCount(2)}");
GC.Collect(0);
Console.WriteLine($"forced 0 {GC.CollectionCount(0)} {GC.CollectionCount(1)} {GC.CollectionCount(2)}");
GC.Collect(2);
Console.WriteLine($"forced 2 {GC.CollectionCount(0)} {GC.CollectionCount(1)} {GC.CollectionCount(2)}");
Console.WriteLine($"memory {GC.GetTotalMemory(false)}");
dotnet run
before 0 0 0
forced 0 1 0 0
forced 2 2 1 1
memory 67296
The gen 0 call incremented only the gen 0 counter. The full collection incremented all three, and its memory is the live set of a program that has allocated almost nothing: the runtime itself.
When GC.Collect is the wrong tool
- Never in a loop or after every request: a full collection stops the world for the time it takes, and the collector already chose the moment.
- Rarely in production code at all. A test or a diagnostic tool that wants a clean slate is the honest case, and it usually pairs the call with GC.WaitForPendingFinalizers.
- When memory stays high, the question is what still refers to the objects, not when the collector runs: a static list, an event that was never unsubscribed, a cache without a limit.
- GC.GetTotalMemory, the counters and a memory profiler answer that question; dotnet-counters and dotnet-dump would be the tools, and neither is in this image.
Exercises
- Build the second program with -c Release and see whether after null changes.
- Keep the strong reference in a static field and watch the weak reference stay alive across a collection.
- Add GC.WaitForPendingFinalizers() after the full collection and explain what it waits for.
- Write a cache of three entries held by weak references and print how many survive after a collection.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does a WeakReference do?
Answer
Points at an object without keeping it alive
Only a strong reference keeps an object; a weak one reports when the target is gone.
-
What does IsAlive report after the target was collected?
Answer
False, and Target is null
The reference can no longer reach a live object, so both answers follow.
-
What does this program print?
var w = Make(); GC.Collect(); Console.WriteLine(w.IsAlive); static WeakReference Make() => new WeakReference(new object());Answer
False
Nothing strong refers to the object after Make returns, so the collection takes it.
-
Why did the local array survive being set to null in a Debug build?
Answer
A Debug build keeps locals alive to the end of the method
Debug code keeps locals for the debugger, so the JIT does not report them dead early.
-
What does GC.Collect(0) collect?
Answer
Generation 0 only
A collection of generation n includes the younger ones, and 0 is the youngest.
-
What does this program print?
GC.Collect(); Console.WriteLine(GC.CollectionCount(2) > 0);Answer
True
The explicit call is a full collection, so the gen 2 counter rises above zero.
-
Why is GC.Collect a bad idea in a request loop?
Answer
Each full collection stops the program while it runs
A full collection is a pause, and the collector already balances pauses against memory.
-
What does GC.WaitForPendingFinalizers do?
Answer
Waits until queued finalizers have run
It blocks the calling thread until the finalizer queue is empty.
-
A program keeps growing in memory. What is the first thing to look for?
Answer
What still holds a reference to the objects
Live objects cannot be collected, so the reference is the bug, not the collector.
-
Which tool would show the heap of a running process, and is it in this image?
Answer
dotnet-dump and dotnet-counters, and neither is installed
The diagnostics tools are separate installs, and this image has none of them.
The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev