What is garbage collection In C# ?

In computing, garbage collection (also known as GC) is a form of automatic memory management. The garbage collector attempts to reclaim the memory used by objects that will never be accessed again by the application. Garbage collection was invented by John McCarthy around 1959 to solve the problems of manual memory management in his recently devised Lisp programming language.
Many computer languages require garbage collection, either as part of the language specification (e.g. Java, C#, Dylan) or effectively for practical implementation (e.g. formal languages like lambda calculus); these are said to be garbage-collected languages.
Other languages were designed for use with manual memory management, but have garbage collected implementations (e.g., C, C++). In either case, it is easier to implement garbage collection as part of the language’s compiler and runtime system. The garbage collector will almost always be closely integrated with the memory allocator.
How does the garbage collector run?
Garbage collector runs in its own thread and runs only when other threads are in a safe state(suspended). When it runs, it needs to move objects and update object references:
• It build a graph of all reachable objects, any object isn’t in this grpah consider unreachable.
• It checks to see the unreachable objects require finalization(destructor). It will place it in freachable queue(pronounced as F-reachable) if it does.
• Remaining unreachable objects are deallocated by moving reachable objects down the heap, thus defragmenting and freeing memory at the top of the heap. While it moves reachable objects, it also updates any references to the objects.
• Now, it allows other threads to resume.
• The freach queue is finalized in a separate thread.
Writing classes with destructors adds complexity to your code and to the garbage collector process which may result making your program run more slowly. So it is recommend to try to avoid using destructors by all mean necessary except when you really need them (consider a using statement instead). Another is to ensure that each destructor reclaims one resource and nothing else.
Scroll to Top