http://www.developer.com/net/csharp/article.php/3343191/C-Tip-Forcing-Garbage-Collection-in-NET.htm
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: If you build and run this example, you will receive the following output: Note a couple of issues here: Download the accompanying code here (17 Kb).
C# Tip: Forcing Garbage Collection in .NET
April 21, 2004
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);
}
}
}
CreateAccount - instantiate Account object
Account::Acount - c'tor
CreateAccount - created account number 111006116
Account::~Acount - d'tor
Application ending
Download