Garbage Collection in .Net

 

Memory management is the critical while developing application which takes a lot of programming time away from developing new code while you track down memory leaks. .NET hopes to do away with all of that within the managed environment with the garbage collection system. Garbage namespace collection runs when your application is running out of free memory, or when it is implicitly called but its exact time of execution cannot be determined. Microsoft provides Garbage Collection to delete the objects manually and automatically.

 

Microsoft .NET CLR is very clever to handle the objects lifetime by using Garbage Collector. When your application requests more memory, and the memory allocator reports that there is no more memory on the managed heap, garbage collection is called. The garbage collector starts by assuming everything in memory is trash that can be freed. It then walks though your application’s memory, building a graph of all memory that is currently referenced by the application. Once it has a complete graph, it compacts the heap by moving all the memory that is genuinely in use together at the start of the free memory heap. After this is complete, it moves the pointer that the memory allocator uses to determine where to start allocating memory from the top of this new heap. It also updates all of your application’s references to point to their new locations in memory. This approach is commonly called a mark and sweep implementation. The exception to this is with individual objects over 20,000 bytes. Very large objects are allocated from a different heap, and when this heap is garbage collected, they are not moved, because moving memory in this size chunks would have an adverse effect on application performance.

 

By default Garbage Collector runs for every 20 minutes to delete the unused objects from memory. Garbage collection involves a lot of work, and it does take some time. A number of performance optimizations involved in the .NET garbage collection mechanism make it much more than the simple description given here. Normally you will just let the CLR take care of running garbage collection when it is required. However, at times you may want to force the garbage collector to run, perhaps before starting an operation that is going to require a large amount of memory. To do this, just call GC.Collect(). By using GC.GetTotalMemory method we can easily find out  the total memory application is taking in bytes while running.

 

You can force the Garbage Collector to delete the objects by using Collect() method as shown below. Microsoft provides the Garbage Collector to delete the objects programmatically in .Net CLR.

 

                                                    GC.Collect();