New In Orcas Part 2: GC Collection Modes

In Orcas we’ve added an overload to System.GC.Collect():

void System.GC.Collect(int generation, System.GCCollectionMode mode)

Where generation is the highest generation to collect (from 0 to System.GC.MaxGeneration) and mode can be:

  • Default:  the same behavior if you called GC.Collect without specifying the mode.  Currently this is the same behavior as Forced, but this is subject to change in future versions of the runtime.
  • Forced:  guarantees a collection occurs for all the generations up to and including generation. 
  • Optimized:  this mode will tell the GC to only collect if it determines that a collection will be productive.  In this case, “productive” is determined by a number of factors, including amount of memory considered garbage, heap fragmentation, etc.  The exact formula is subject to change between CLR releases.  If the GC decides a collection will not be productive, then the call will have no effect.

When should we use these new modes?

Calling GC.Collect is generally discouraged, but as Rico points out here, there are legitimate circumstances where you know there is a large number of objects you’ll never need again.  For example, at the end of a game level, when a custom Form is closed, or when a web form is finished, there may be a number of long-lived objects in generation 2 that are now dead.  By calling an Optimized collection at this point you give the GC a chance to evaluate the heap, and have it decide if a collection will free enough memory to be worth it.

Forced and Default modes should generally only be used for debugging or testing scenarios, where you want to ensure objects are collected at a certain point in your application, or want to compare performance data.  In future versions of the CLR, there may be new guidance for using Default, but for now, its use is discouraged.