Introduction of Garbage Collection in C#
When any object is created in C#, CLR (common language runtime) allocates memory for the object from heap.
This process is repeated for each newly created object, but there is a limitation to everything, Memory is not un-limited
and we need to clean some used space in order to make room for new objects, Here, the concept of garbage collection
is introduced- So, Garbage Collector
is nothing but, it is a feature provided by CLR which helps us to clean or destroy the unused managed objects.
By cleaning or destroying those unused managed objects, basically reclaims the memory.
When a dot net application (in our case let's say C# application) runs, it creates many objects and at a given moment of time, it may possible
that the application may not use some of those objects.
So, for those objects, Garbage Collector runs continuously as a background thread
and at specific interval time, it checks whether
there are any unused managed objects (Note: The Garbage Collector will destroy only the unused managed objects. It does not clean unmanaged objects. ) and if it finds it simply clean those objects and reclaims the memory.
How GC works in C# ?
GC works on managed heap, which is nothing but a block of memory to store objects, when garbage collection process is put in motion, it checks for dead objects and the objects which are no longer used, then it compacts the space of live object and tries to free more memory.
What is Generation in C# GC?
Basically, heap is managed by different 'Generations', it stores and handles long-lived and short-lived objects, see the below generations of Heap:
So, in simple words, we can say that Generations 0, 1, and 2 will helps to increase the performance of the Garbage Collector. The more the objects in Gen 0, the better the performance and the more the memory will be utilized in an optimal manner.
When GC gets triggered?
There are no specific timings for GC to get triggered, GC automatically starts operation on the following conditions:
GC.Collect()
method explicitly, as GC runs continuously, we actually do not need to call this method.GC vs Destructor
When you define a destructor in your class, the Garbage Collector before disposing of the object, will go and ask the question to the class, do you have a destructor, if you have a destructor, then move the object to the next generation bucket. In other words, it will not clean up the object having destructor at that moment itself even though it is not used. So, it will wait for the destructor to run, and then it will go and clean up the object. Because of this, you will find more objects in generation 1 and Generation 2 as compared to Generation 0.
Clean Up Unmanaged Resources
When we create unmanaged objects, GC is unable to clear them and we need to release such objects explicitly when we finished using them. Mostly unmanaged objects are wrapped/hide around operating system resources like file streams, database connections, network related instances, handles to different classes, registries, pointers etc.
GC is responsible to track the life time of all managed and unmanaged objects but still GC is not aware of releasing unmanaged resources. There are different ways to cleanup unmanaged resources:
IDisposable
interface and Dispose()
methodThere are couple of ways to implement Dispose method:
Implement Dispose using SafeHandle
Class:
class clsDNP_Dispose { // Take a flag to check if object is already disposed bool bDisposed = false; // Create a object of SafeHandle class SafeHandle objSafeHandle = new SafeFileHandle(IntPtr.Zero, true); // Dispose method (public) public void Dispose1() { Dispose(true); GC.SuppressFinalize(this); } // Dispose method (protected) protected virtual void Dispose(bool bDispose) { if (bDisposed) return; if (bDispose) { objSafeHandle.Dispose(); // Free any other managed objects here. } // Free any unmanaged objects here. // bDisposed = true; } }
Implement Dispose using overriding the Object.Finalize
method:
class clsDNP_Finalize { // Flag: Has Dispose already been called? bool disposed = false; // Public implementation of Dispose pattern callable by consumers. public void Dispose() { Dispose1(true); GC.SuppressFinalize(this); } // Protected implementation of Dispose pattern. protected virtual void Dispose1(bool disposing) { if (disposed) return; if (disposing) { // Free any other managed objects here. // } // Free any unmanaged objects here. // disposed = true; } ~clsDNP_Finalize() { Dispose1(false); } }
Summary
To summarize, Garbage collector manages allocation and reclaim of memory. Managed objects are created, managed and under scope of CLR whereas unmanaged resources can be cleaned-up using 'Dispose' method and 'using' statement. Most important thing is - there is no specific timings for GC to get triggered, GC automatically start operation.
Cheers!