#937 – Forcing a Garbage Collection

The garbage collector (GC) normally runs automatically, doing a garbage collection pass when necessary (when there is memory pressure and you are allocating memory for some new object).

You typically just let the garbage collector run automatically, never explicitly asking it to do garbage collection.

For testing purposes, however, you might want to force garbage collection to happen at a particular time.  You can do this by calling the GC.Collect method.  Calling Collect will force a collection across all generations.  You can also specify the highest generation to collect as follows:

  • GC.Collect() – Collect generations 0, 1, 2
  • GC.Collect(0) – Collect generation 0 only
  • GC.Collect(1) – Collect generations 0, 1

Objects with finalizers will not be collected when you call Collect, but rather placed on the finalization queue.  If you want to also release memory for these objects, you need to wait until their finalizers are called and then do another garbage collection pass.

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
Advertisements