Garbage Collection
suggest changeVersions
The garbage collector has been part of the .NET Framework since 1.0. The behavior described here applies through 4.6.2.
Introduction
In .NET, objects created with new are allocated on the managed heap. The program does not free that memory itself; the .NET garbage collector does. Finalizers, if any, also run under the collector's control.
Some of the examples below are lab cases that show the garbage collector at work. Others focus on how to prepare classes for it.
Remarks
The garbage collector reduces the amount of memory a program keeps, at the cost of processing time. A few points matter when you program with it in mind:
- Do not call
GC.Collectin ordinary code. If you must,GCCollectionMode.Optimizedlets the collector skip the collection when it would not be productive. It is not a mode that finalizes objects only when memory is low. - For large unmanaged allocations the collector cannot see, call
GC.AddMemoryPressureandGC.RemoveMemoryPressure. That informs the collector; it does not itself free the unmanaged block. - A collection does not promise to finalize every dead object. The collector uses three generations, and an object can survive from one generation into the next.
- Workstation and server GC, and background GC, change how much the collector pauses application threads.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents