The thing with quasi-religious beliefs is that they tend to repeatedly come up throughout the circle of life.
Just recently, I reviewed a friend’s code where he implemented the Dispose Pattern horribly wrong, involving a call to GC.Collect().
And today, a coworker on an internal distribution list refers to Rico Mariani’s "When to call GC.Collect()" post from 2004, and, in particular, at the comments to that post, indicating there could be something complicated or unresolved in this matter.
To me, it’s quite simple.
To avoid manifestation of superstitious rituals, let me quote Rico’s main rules (emphasis mine):
This is really the most important rule. It’s fair to say that most usages of GC.Collect() are a bad idea and I went into that in some detail in the original posting so I won’t repeat all that here. So let’s move on to…
Consider calling GC.Collect() [only] if some non-recurring event has just happened and this event is highly likely to have caused a lot of old objects to die.
In addition, let me also quote from the memory usage post Rico refers to in the first paragraph:
Almost-rule #1: Never call GC.Collect()
If you think you need to force a collection something has gone very wrong. You have to ask yourself, what sort of collection do I think I need? Gen0, Gen1, Gen2? How do I know that the GC will decide to do the collection that I think I need? What did I do so that now I need that kind of collection?
And, while we’re at it:
Almost-rule #2: Never have finalizers
(except on leaf objects which hold a single unmanaged resource and nothing else)
Checking in code using GC.Collect() should be allowed only after providing strong evidence and after several rounds of code review.
And never, never, never call GC.Collect in the Dispose method. Never. This is like trying to empty a waste bin with a stick of Dynamite.
Please, don’t call GC.Collect(). Help Make Software Better.™
Just my 2¢ after reading the garbage collection post and the comments, especially contrasting those from Darren Oakey and Ian Griffiths.