Managed resources
Managed resources are the objects you create on the heap in your C# code by calling new
. Before going into ways to save memory taken by managed resources, let's have a quick look at their life cycle.
Life cycle
When you call new
to create an object, memory is allocated for it on the CLR-managed heap. This always happens from the end of the allocated area, which makes it very quick.
When the CLR tries to allocate memory for an object and finds that enough space is not present at the end of the allocated area, it initiates a garbage collection. This removes all objects that no longer have references, and compresses all the surviving objects. The result is a nice, contiguous space at the end of the allocated area.
Once all references to an object disappear because they have gone out of scope or because they have been set to null, the object becomes eligible for garbage collection. However, it only gets physically removed by the next garbage collection, which may not happen for...