CodeQL documentation

Call to GC.Collect()

ID: cs/call-to-gc
Kind: problem
Security severity: 
Severity: warning
Precision: very-high
Tags:
   - 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.

Recommendation

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.

Example

using System;

class Bad
{
    void M()
    {
        GC.Collect();
    }
}

References

  • © GitHub, Inc.
  • Terms
  • Privacy