Why is this an issue?
GC.Collect is a method that forces or suggests to the garbage collector to run a collection of objects in the managed heap
that are no longer being used and free their memory.
GC.Collect is rarely necessary and can significantly affect application performance. That’s because it is a tracing garbage collector and needs to examine every object in memory for
cleanup and analyze all reachable objects from every application’s root (static fields, local variables on thread stacks, etc.).
To perform tracing and memory releasing correctly, the garbage collection may need to block all threads currently in execution. That is
why, as a general rule, the performance implications
GC.Collect far outweigh the benefits.
This rule raises an issue when any overload of
Collect is invoked.
static void Main(string args)
GC.Collect(); // Noncompliant
GC.Collect(2, GCCollectionMode.Optimized); // Noncompliant
There may be exceptions to this rule: for example, you’ve just triggered some event that is unique in the run of your program that caused a lot of
long-lived objects to die, and you want to release their memory.