Stats

41 Contributors: 1
2017-04-05
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook

Garbage Collection

Download .net eBook

Introduction

In .Net, objects created with new() are allocated on the managed heap. These objects are never explicitly finalized by the program that uses them; instead, this process is controlled by the .Net Garbage Collector.

Some of the examples below are "lab cases" to show the Garbage Collector at work and some significant details of its behavior, while other focus on how to prepare classes for proper handling by the Garbage Collector.

Remarks

The Garbage Collector is aimed to lower the program cost in terms of allocated memory, but doing so has a cost in terms of processing time. In order to achieve a good overall compromise, there are a number of optimizations that should be taken into consideration while programming with the Garbage Collector in mind:

  • If the Collect() method is to be explicitly invoked (which should not often be the case anyway), consider using the "optimized" mode which finalizes dead object only when memory is actually needed
  • Instead of invoking the Collect() method, consider using the AddMemoryPressure() and RemoveMemoryPressure() methods, which trigger a memory collection only if actually needed
  • A memory collection is not guaranteed to finalize all dead objects; instead, the Garbage Collector manages 3 "generations", an object sometimes "surviving" from a generation into the next one
  • Several threading models may apply, depending on various factors including setup fine tuning, resulting in different degrees of interference between the Garbage Collector thread and the other application thread(s)

Related Examples