Forcing Garbage Collection in .NET

There might be times in your application when you want to force the .NET Garbage Collector (GC) to spin through all unused objects and de-allocate them. The method for accomplishing this task is the GC.Collect method. When you call GC.Collect, the GC will run each object's finalizer on a separate thread. Therefore, another method to keep in mind is GC.WaitForPendingFinalizers. This synchronous method that will not return until the GC.Collect has finished its work.

Here's a simple example of using these two methods:

using System;

namespace GCCollect
{
  class Account
  {
    public Account(string accountNumber)
    {
      this.accountNumber = accountNumber; 
      Console.WriteLine("Account::Acount - c'tor");
    }
    ~Account() 
    {
      Console.WriteLine("Account::~Acount - d'tor");
    }

    protected string accountNumber;
    override public string ToString() { return accountNumber; }
  };

  class Class1
  {
    [STAThread]
    static void Main(string[] args)
    {
      CreateAccount("111006116");

      GC.Collect();
      GC.WaitForPendingFinalizers();

      Console.WriteLine("Application ending");
    }

    public static void CreateAccount(string accountNumber)
    {
      Console.WriteLine("CreateAccount - instantiate Account object");
      Account account = new Account(accountNumber);
      Console.WriteLine("CreateAccount - created account number {0}",
                        account);
    }
  }
}

If you build and run this example, you will receive the following output:

CreateAccount - instantiate Account object
Account::Acount - c'tor
CreateAccount - created account number 111006116
Account::~Acount - d'tor
Application ending

Note a couple of issues here:

  1. I allocated the Account object in a different method than the Main method. This is because if I allocated the Account object in the Main method and then called GC.Collect in the same method, the Account object would technically still be associated with running code and would therefore not be eligible for collection.
  2. While I used a simple single object example here to illustrate calling the GC.Collect method, the GC.Collect method is designed not to control specific object destruction, but to allow for the forcing of collection for all of unused objects. Therefore, it's a very expensive operation and should only be used in cases where you want/need to force global collection.
  3. For situations where you want to force the finalization of a specific object, you should implement the Dispose pattern, which I'll cover in a separate article.

Download

Download the accompanying code here (17 Kb).



About the Author

Tom Archer - MSFT

I am a Program Manager and Content Strategist for the Microsoft MSDN Online team managing the Windows Vista and Visual C++ developer centers. Before being employed at Microsoft, I was awarded MVP status for the Visual C++ product. A 20+ year veteran of programming with various languages - C++, C, Assembler, RPG III/400, PL/I, etc. - I've also written many technical books (Inside C#, Extending MFC Applications with the .NET Framework, Visual C++.NET Bible, etc.) and 100+ online articles.

Downloads

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Java developers know that testing code changes can be a huge pain, and waiting for an application to redeploy after a code fix can take an eternity. Wouldn't it be great if you could see your code changes immediately, fine-tune, debug, explore and deploy code without waiting for ages? In this white paper, find out how that's possible with a Java plugin that drastically changes the way you develop, test and run Java applications. Discover the advantages of this plugin, and the changes you can expect to see …

  • Live Event Date: August 13, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT If you are developing applications, you'll want to join us to learn how applications are changing as a result of gesture recognition. This technology will change how you and your users interact - not simply with your devices, but with the world around you. Your devices will be able to see and hear what your users are doing. Are your applications ready for this? Join us to learn about Intel® RealSense™ Technology, including never been …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds