In this article I will give you an introduction of how C# garbage collector works.
In shortly I can introduce garbage collector as a worker which runs on separate thread and keeps the developer away by the memory management of the program.
Basically it gives two advantages to the programmers
- Programmers can mainly focus on the logic of the program - in early languages such as unmanaged C++ programmers have to spend lot of their development effort on this memory management, even for well experienced programmers.
- Second one is it helps to keep integrity of the program, if you have ever used unmanaged C++ you may experienced, How many times trying to de allocate memory of object which is already de-allocated. I'm sure at least once
So garbage collector keeps you away by this burden of memory management. By the way it can do the job perfectly.
So if the garbage collector doing it's job perfectly, how is it?
To answer this question you must first understand the way memory is used by the C# program. Basically there are two parts in the memory, called stack and heap.
You must know few things about Stack
Stack is:-
- is considerably small and keeps the references to the heap objects.
- Each new Thread creates new stack frame.
- Value types (structs in C#-usually 16bytes or less) are used to live in the stack.
- Faster in accessing stack elements.
Heap is:-
- Large memory area and all the objects (reference types) used to live in the heap.
- You can not directly access the elements in heap without any reference from the stack.
Garbage Collector Algorithm
Each thread use to create new stack in the memory, as I told above this stack contains the pointers to the objects in the heap. This pointer refers to an object in the heap or it is null. (If we tried to access null pointer it throws NullReferenceException in .Net Framework)
So now we will move on to garbage collection algorithm. When garbage collection starts it assumes that all objects in the heap are as garbage.
Then garbage collector achieves its goal by three phases:
Phase 1: Examine phase
In this phase garbage collector identify roots by examine the thread stack. What are these roots in our c# class?
Usually
- Static fields
- Method Parameters
- Local Variables
- CPU registers
These four types can be identified as roots in our class.
Keep in mind that value types are never become roots, because as I told above they used to live in the stack and destroys when stack blows.
Phase 2: Marking phase
During this phase what garbage collector doing is when it is moving through the thread stack while identifying the roots, if it finds out that root refers to an object in the heap (this means the object is accessible to the outside world)marks it.
Marking is done by turning on the sync block of the each object.




Vahaj uddinPosted Nov 15, 2011, 11:01 AM
Thank You :)