Explicitly Triggering Garbage Collection in C#
A common interview question involves forcing garbage collection in C#. While generally discouraged, understanding how to do this is valuable. This article explains the method, emphasizing that direct GC calls are usually unnecessary.
The Solution:
To manually initiate garbage collection, use this code:
<code class="language-csharp">GC.Collect(); GC.WaitForPendingFinalizers();</code>
GC.Collect()
directly invokes the garbage collector. Crucially, GC.WaitForPendingFinalizers()
must follow to guarantee the execution of all pending finalization operations.
The above is the detailed content of How Can I Force Garbage Collection in C#?. For more information, please follow other related articles on the PHP Chinese website!