CodeBlanks Logo Icon CodeBlanks

GC.Collect

C# course · Expert · Lesson 4/47

Learn memory management with GC.Collect and GC.GetTotalMemory.

GC.Collect and GC.GetTotalMemory

GC.Collect() forces the garbage collector to run. It is generally discouraged because it disrupts the GC's own scheduling; use it only when memory must be freed at a known point.

GC.GetTotalMemory(false) returns the approximate number of managed bytes; with true it waits for collection. The value is useful for measurement and debugging.

The WaitForPendingFinalizers pattern

After GC.Collect, call GC.WaitForPendingFinalizers() so finalizers run. This is used when you want finalizer-bearing classes to release their resources right away.

The typical pattern is Collect → WaitForPendingFinalizers → Collect. The second Collect reclaims the memory that the finalizers freed. This pattern is also useful in measurement and test code to obtain consistent memory readings.

Exercise Collect and print a message

In Main first call GC.Collect();, then GC.WaitForPendingFinalizers();, finally Console.WriteLine("Collected");.

Show example solution
Write GC.Collect(); GC.WaitForPendingFinalizers(); Console.WriteLine("Collected");
Example solution:
using System;

class Program
{
    static void Main()
    {
        GC.Collect();
        GC.WaitForPendingFinalizers();
        Console.WriteLine("Collected");
    }
}

Test yourself

  1. Match the GC methods

    GC.Collect()
    Force collection
    GC.GetTotalMemory(false)
    Approximate memory
    GC.WaitForPendingFinalizers()
    Waits for finalizers
    GC.KeepAlive(o)
    Keeps object alive
  2. When is GC.Collect() recommended?

    • After every method call
    • Performance measurement or a specific point
    • In every loop
    • Always at program start
    Show answer

    Performance measurement or a specific point — Correct. GC.Collect is used only for special cases, like measurement.

  3. Force a collection

    GC.____();
    GC.WaitForPendingFinalizers();
    Show answer
    GC.Collect();
    GC.WaitForPendingFinalizers();

All lessons in Expert