How can I write a unit test to determine whether an object can be garbage collected?

This is what I normally do:

[Test]
public void MyTest() 
{
    WeakReference reference;
    new Action(() => 
    {
        var service = new Service();
        // Do things with service that might cause a memory leak...

        reference = new WeakReference(service, true);
    })();

    // Service should have gone out of scope about now, 
    // so the garbage collector can clean it up
    GC.Collect();
    GC.WaitForPendingFinalizers();

    Assert.IsNull(reference.Target);
}

NB: There are very, very few times where you should call GC.Collect() in a production application. But testing for leaks is one example of where it’s appropriate.

Leave a Comment