#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();
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #937 – Forcing a Garbage Collection

  1. Pingback: Dew Drop – September 24, 2013 (#1,630) | Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: