Garbage Collector in C#

Garbage Collector

Garbage Collector is responsible for automatic memory management. As name is garbage collector it collect the object which is not reachable for long time. Memory is divided in 3 Generation as Gen 0, Gen 1,Gen 2 as showing in below figure.

Generation in Garbage Collector
Figure: Generation in Garbage Collector

Newly created object store in Gen 0 and this process will repeat till Gen 0 get full. When Gen 0 will be full then there will be 2 Phases of Process. In 1st phase of process it makes the marks the object about reachable and unreachable in the memory. The object which is not reachable means which object has no use for long time it make as unreachable objects. In 2nd phase of process it remove the object which has marked as unreachable ,and transfer the reachable object from Gen 0 to Gen1 .This same process will be follow to transfer the object from Gen 1 to Gen 2 . There is some methods which use to remove unreachable object from memory.

Dispose method

Dispose () use to remove the unreachable object from memory or object which has no references. Dispose (). This method call by Developer.

Finalize method

Finalize () clean up the object from memory which has no references. Finalize () method get call by System.

Gc.Collect method

gc.Collect () method use to remove the object forcible from memory.

Recap

Garbage Collector is responsible for automatic memory management which removes the object from memory which has not references.

Ebook Download
View all
Learn
View all