Please explain about the Garbage Collector in .net framework.
What Is Garbage Collector ?
145212-Dec-2019
Updated on 12-Dec-2019
Home / DeveloperSection / Forums / What Is Garbage Collector ?
Please explain about the Garbage Collector in .net framework.
Nishi Tiwari
13-Dec-2019Common Language runtime (CLR) also responsible for containing Garbage Collector (GC) which is low priority thread and checks for unreferenced objects. If it finds some data that is no more referenced by any variable/reference, GC reclaims it and returns memory back to the operating system so that it can be used by other programs and presence of standard Garbage Collector makes programmers free from dangling data.
.Net framework provides a mechanism for releasing unreferenced objects from memory, this process is known as Garbage Collection. When programs creates an object it takes up memory space. Later when program has no longer use of objects, objects becomes unreachable and cannot be immediately free. Garbage collection checks for objects that are no longer being used by any application. If such objects exits then memory occupy by these objects must be reclaimed or free so that memory can be used by other objects. This releasing of unreferenced objects is happening automatically in .Net Languages by Garbage Collector.
Another definition for garbage collector
.NET’s garbage collector is the explicit memory management, and of memory leaks, in Windows applications. When garbage collector running in the background, developers no longer need to worry about the need to manage the life-cycle of the objects that has been created ,the garbage collector will solve the problem once the application has been finished.
The garbage collector solves the most common leaks in unmanaged programs – those caused by developers if they forgetting to release memory when they have finished. It also fix the problem of memory being released too early, but the way in which this is solved can lead to memory leaks when the garbage collector has a different opinion than the developer about whether or not an object is still ‘live’ and able to be used.
How the garbage collector works?
When a garbage collection process starts, it looks at a references called the ‘GC roots’. These are memory locations which contain references to objects created by the program. It marks these objects as ‘live’ and then looks at any objects that they reference; it marks those objects as being ‘live’ too. It continues, through all of the objects it knows are ‘live’.
Once all live objects are known, any remaining objects can be released and the space re-used for new objects. .NET manages memory so that there are no gaps means that free memory is always located at the end of a heap and makes allocating new objects very fast.
GC roots are references to objects. Any object referenced by a GC root will automatically survive the next garbage collection.