BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

.NET Framework
.NET 1.1

Forcing Garbage Collection

The garbage collector controls memory management automatically, deallocating memory used by unreachable objects periodically but unpredictably. In some situations it can be useful to force an immediate complete or partial garbage collection.

Garbage Collection

In an earlier article I described the garbage collection process used by the .NET framework to provide automatic memory management. The garbage collector runs when memory in the managed heap is low. It scans the heap for dead objects, removes them and defragments the heap by moving the surviving objects so that they remain contiguous. This means that, in general, you do not need to worry about memory management or the risk of objects leaking memory.

The garbage collection process can affect the performance of your applications, as when it executes it stops the program until the deallocation of memory is complete. For large numbers of objects and full garbage collections this can take a noticeable amount of time. To limit the number of times that the garbage collector runs, and the associated performance impact, you can follow the guidelines described in the earlier article.

In the vast majority of cases you should allow the garbage collector to run automatically as memory pressure becomes high. However, there are some circumstances where it may be beneficial to force garbage collection. Two examples of such situations are:

  • you have just released a very large number of objects. For example, the user may have closed a large document, causing thousands of objects to become unreachable. It can make sense to deallocate the memory used by the closed document straight away.
  • you are about to perform a performance-critical operation that generates a lot of objects and may cause the garbage collector to start. For example, if you are performing real-time audio or video processing it may be useful to run the garbage collector beforehand. This should reduce the risk of it commencing during the processing and causing a "stutter".

GC.Collect

To force garbage collection you can execute the static Collect method of the GC class. To perform a complete collection, call the method with no arguments, as follows:

GC.Collect();

You can also force a partial collection by using an overloaded version of the method. This allows you to provide an integer value to its single parameter. This specifies a generation number. Objects of this, or a lower, generation are eligible for collection.

The sample code below forces a garbage collection for dead objects in generation zero and generation one. Generation two objects will not be considered for deallocation.

GC.Collect(1);
8 November 2012