When is it acceptable to call GC.Collect?

If you have good reason to believe that a significant set of objects – particularly those you suspect to be in generations 1 and 2 – are now eligible for garbage collection, and that now would be an appropriate time to collect in terms of the small performance hit.

A good example of this is if you’ve just closed a large form. You know that all the UI controls can now be garbage collected, and a very short pause as the form is closed probably won’t be noticeable to the user.

UPDATE 2.7.2018

As of .NET 4.5 – there is GCLatencyMode.LowLatency and GCLatencyMode.SustainedLowLatency. When entering and leaving either of these modes, it is recommended that you force a full GC with GC.Collect(2, GCCollectionMode.Forced).

As of .NET 4.6 – there is the GC.TryStartNoGCRegion method (used to set the read-only value GCLatencyMode.NoGCRegion). This can itself, perform a full blocking garbage collection in an attempt to free enough memory, but given we are disallowing GC for a period, I would argue it is also a good idea to perform full GC before and after.

Source: Microsoft engineer Ben Watson’s: Writing High-Performance .NET Code, 2nd Ed. 2018.

See:

Leave a Comment