← 返回首页
Call to GC.Collect() — CodeQL query help documentation CodeQL docs
CodeQL documentation
CodeQL resources

Call to GC.Collect()

ID: cs/call-to-gc Kind: problem Security severity: Severity: warning Precision: very-high Tags: - quality - reliability - performance Query suites: - csharp-code-quality.qls - 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