CodeQL documentation

Call to GC.Collect()

ID: cs/call-to-gc
Kind: problem
Severity: warning
Precision: very-high
   - efficiency
   - maintainability
Query 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.


Remove the explicit call to GC.Collect() and run a memory profiler to optimize your application’s memory usage. If your application uses unmanaged resources and calls GC.Collect() to force finalizers to run, it is better to implement the IDisposable pattern and use try/finally clauses to make sure that unmanaged resources are disposed of even if an exception interrupts your application.


using System;

class Bad
    void M()