The garbage collector serves as an automatic memory manager.
When you create any object 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, Garbage collector manages allocation and reclaiming of memory. GC (Garbage collector) makes a trip to the heap and collects all objects that are no longer used by the application and then makes them free from memory. When any process gets triggered, separate virtual space is assigned to that process, from a physical memory.
Virtual memory has three blocks:
• Free (empty space)
• Reserved (already allocated)
• Committed (This block is give-out to physical memory and not available for space allocation)
GC checks the below information to check if the object is live:
• It collects all handles of an object that are allocated by user code or by CLR
• Keeps track of static objects, as they are referenced to some other objects
• Use stack provided by stack walker and JIT
GC automatically starts operation on the following conditions:
1. When virtual memory is running out of space.
2. When allocated memory is suppressed acceptable threshold (when GC found if the survival rate
(living objects) is high, then it increases the threshold allocation).
3. When we call GC.Collect() method explicitly, as GC runs continuously, we actually do not need to call this method.
There are different ways to cleanup unmanaged resources:
• Implement IDisposable interface and Dispose method
• 'using' block is also used to clean unmanaged resources