Call to GC.Collect()¶
ID: cs/call-to-gcKind: problemSecurity severity: Severity: warningPrecision: very-highTags: - quality - reliability - performanceQuery suites: - csharp-security-and-quality.qls
Click to see the query in the CodeQL repository
Explicitly forcing garbage collection is not efficient and is almost never necessary outside of benchmarking scenarios.
Recommendation¶
Remove the explicit call toGC.Collect() and run a memory profiler to optimize your application’s memory usage. If your application uses unmanaged resources and callsGC.Collect() to force finalizers to run, it is better to implement theIDisposable pattern and usetry/finally clauses to make sure that unmanaged resources are disposed of even if an exception interrupts your application.
Example¶
usingSystem;classBad{voidM(){GC.Collect();}}
References¶
Microsoft:Profile Memory Usage in Visual Studio.