What is a garbage collector?
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.
Read for more questions on Garbage collector in .NET.
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.
Following we have also video on Garbage Collector, Gen 0, 1 & 2 which explains in more detail: -
Garbage collector cleans managed code, 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.
Also get to learn more on the basics of .NET