
The C# language is a garbage-collected language, which means that memory that is no longer referenced by your program will be reclaimed and can later be reused. With the GC.Collect method, you can force a garbage collection to occur at any time. The GC.Collect method is effective but you should be wary of its use.
This C# example program demonstrates the GC.Collect method. It forces a garbage collection.
First, this example demonstrates the effect of invoking the GC.Collect method. Three calls to get the total memory usage on the system are present: they occur before the allocation, after the allocation, and after the forced garbage collection. You can see that memory returns to its low level after the garbage collection.
Program that uses GC.Collect [C#]
using System;
class Program
{
static void Main()
{
long mem1 = GC.GetTotalMemory(false);
{
// Allocate an array and make it unreachable.
int[] values = new int[50000];
values = null;
}
long mem2 = GC.GetTotalMemory(false);
{
// Collect garbage.
GC.Collect();
}
long mem3 = GC.GetTotalMemory(false);
{
Console.WriteLine(mem1);
Console.WriteLine(mem2);
Console.WriteLine(mem3);
}
}
}
Output
45664
245696
33244
GC.GetTotalMemory Usage
So when should you call the GC.Collect method in your .NET programs? In my experience, the answer is basically never: the call will usually not do much to reduce overall memory usage, and it will impose a slowdown whenever it is called. In ASP.NET, the GC.Collect on one application will cause a performance hit on all web sites in the same pool.

Essentially, GC.Collect adds more complexity to your program and probably even reduces overall performance. The .NET garbage collector is finely tuned and benchmarked by Microsoft, and they have more time and money to spend on tweaking its performance than you do. As is typical for me, I have used GC.Collect in attempts to improve performance, particularly after a lot of allocations after startup, and this proved to be a waste of effort.
The GC.Collect is best used for diagnostics purposes, such as for determining a baseline of memory usage in your program. You can also use it to see if all the objects you no longer need are not reachable and can be collected by the garbage collector. However, in deployment, the GC.Collect method is not useful because it often has little benefit and might even reduce performance, while increasing complexity and causing you headaches.
.NET Framework Info