Can you force .Net garbage collection?


Confusion exists on whether .Net’s GC.Collect() simply suggests or actually forces garbage collection (GC). Thankfully, developers don’t usually need to worry about such mundane details. However, in unusual circumstances—like WeakReference testing (which may rely on predictable, guaranteed destruction of unneeded objects)—particulars like this become vitally important.

Can the garbage collection process be forced to run?

MSDN says that GC.Collect() “forces garbage collection.” This is as clear as can be. Calling GC.Collect() doesn’t request or suggest garbage collection—when it is called, collection always occurs.

When collection is induced, will all eligible objects be destroyed?

Calling GC.Collect() destroys all non-finalizable collection-eligible objects. Finalizable object destruction involves two additional steps (assuming that no object resurrection occurs): after the initial GC.Collect() call, wait for the finalizers to run, then call GC.Collect() a second time. In both cases, the collector will not mysteriously skip over eligible objects. Any object which qualifies for destruction will be discarded.

Destroying an object is different from freeing the memory used by the object. If a WeakReference points to an object which is garbage collected, the WeakReference’s IsAlive property will equal false—the object has been destroyed. However, sometimes it is inefficient for the garbage collector to free up the memory used by the destroyed object. GC.Collect()‘s documentation alludes to this with the word “try” when it says “Use this method to try to reclaim all memory that is inaccessible” (emphasis mine). The object has been destroyed even if the memory it used has not been released.

Closing Thoughts

Other programming languages’ garbage collection implementations may operate differently. It’s important not to confuse the specifics of how they work with how .Net works.

For details on how .Net determines when an object is eligible for garbage collection, read Jeffrey Richter’s MSDN Magazine article Garbage Collection: Automatic Memory Management in the Microsoft .NET Framework.

Thanks goes to Maoni Stephens for helping me understand several pertinent garbage collection particulars.

Leave a Reply

Your email address will not be published. Required fields are marked *