Garbage collector is a feature of CLR which cleans unused managed (it does not clean unmanaged objects) objects and reclaims memory. It’s a back ground thread which runs continuously and at specific intervals it checks if there are any unused objects whose memory can be claimed.
Note: - GC does not claim memory of unmanaged objects.
Note: - Garbage collector is one of the very important interview topics due to complexity of generations, double GC loop because of destructor and the implementation of finalize and dispose pattern.What are generations in Garbage collector (Gen 0, 1 and 2)?
Generations defines age of the object. There are three generations:-
- Gen 0:- When application creates fresh objects they are marked as Gen 0.
- Gen 1:- When GC is not able to clear the objects from Gen 0 in first round it moves them to Gen 1 bucket.
- Gen 2:- When GC visits Gen 1 objects and he is not able to clear them he moves them gen 2.
Generations are created to improve GC performance. Garbage collector will spend more time on Gen 0 objects rather than Gen 1 and Gen 2 thus improving performance.
Note: - More the objects in Gen 0, more your application is stable.
Garbage collector cleans managed code then how do we clean unmanaged code?
Garbage collector only claims managed code memory. For unmanaged code you need to put clean up in destructor / finalize.
Can we force garbage collector to run?
“System.GC.Collect ()” forces garbage collector to run. This is not a recommended practice but can be used if situations arise.
But when we create a destructor the performance falls down?
Yes, when we define a destructor, garbage collector does not collect these objects in the first round. It moves them to Gen 1 and then reclaims these objects in the next cycle.
As more objects are created in Gen 1 the performance of the application falls down because more memory is consumed.
Also see following .NET interview questions video on Garbage Collector - Gen 0, 1 & 2: -