Sobes.tech
Junior — Middle

How can you manually trigger garbage collection in C#?

sobes.tech AI

Answer from AI

In C#, the method GC.Collect() is used for manual garbage collection. This method initiates an immediate attempt to collect garbage, freeing unused memory.

Example:

// Forcing garbage collection
GC.Collect();
// Optionally, wait for finalizers to complete
GC.WaitForPendingFinalizers();

However, it is recommended to use this method with caution, as the garbage collector in .NET is optimized for automatic memory management, and forced calls can degrade application performance.

How can you manually trigger garbage collection in… - sobes.tech