Mar 31, 2019

.net garbage collection

The garbage collector serves as an automatic memory manager. After the garbage collector is initialized by the CLR, it allocates a segment of memory to store and manage objects. When a garbage collection is triggered, the garbage collector reclaims the memory (managed memory) that is occupied by dead objects. The reclaiming process compacts live objects so that they are moved together, and the dead space is removed, thereby making the heap smaller.

If your managed objects reference unmanaged objects, you will have to explicitly free them (unmanaged objects). .NET does not allocate Unmanaged memory, as it's coming from outside sources and thus the GC doesn't know about it.  For example, when you open a file (FileStream) you are basically calling (behind the scenes) the CreateFile unmanaged Win32 function. This function allocates an unmanaged file handle directly from the file system. .NET and the GC has strictly no way of tracking this unmanaged object and everything it does.

To handle this you have IDisposable and Dispose, which you will implement in your managed object, where you will clean up your unmanaged memory (if any created by your object) and implement the finalizer to call Dispose(). The finalizer is just a safeguard, it will make sure that those resources get cleaned up eventually if the caller forgets to dispose of your class properly.

.Net provides using statement, which is a convenient syntax that ensures that Dispose is called (even if an exception occurs in using block) as soon as execution reaches close brace.

Garbage collection occurs when the system has low physical memory or the memory used by allocated objects on the managed heap surpasses an acceptable threshold. You also have an option of calling GC.Collect, but most likely you do not have to call this, it's only in some unique situation you will be using this function.

The heap is organized into generations so it can handle long-lived or short-lived object. Refer following for more detail.