.Net Concepts

Garbage Collection (GC)


Hi, if some one asks you what is Garbage Collection in .Net? What thoughts comes into your mind?

Let me share my knowledge here:

Brief description: Garbage Collection is the process handled by a .Net special class which claims the memory from the application when the memory is not in use or it is not needed by the application any more.



So, now you might have got the basic idea on GC. Lets go deeper into this to understand how everything works behind the scene.

Consider, you have started a .Net application and it is running. Before it runs, there are few things that happens as part of OS to execute. This is another story, lets not discuss this here. Once application starts running.

Let say, you have clicked a button in the application and it calls a function. Ex:

public void AddCustomer(Customer c)
{
      //Before you add customer to your storage (DB or anything), let say you need to deal some         objects here

    ClassA a = new ClassA();

    ....some code here........

   ClassB b = new ClassB()
   .....some code here.......


  do some thing at the end of the code and add save your customer to DB

}

In the above function, you have created 2 objects a and b. For these 2 objects there will be 2 blocks of memory assigned in our system memory based on the CLR calculation of the memory size (How it calculates the memory for an object? I will come to this later)

Once function instructions are done, it comes out of the function code. Now, what happens to these 2 objects? Are they cleaned up immediately as soon as scope goes out?

Answer is NO. Because, they exists in memory. This is where, GC comes into picture. How GC handles memory cleanup. In simple words, it maintains 3 states or generations of the objects

1) Youngest objects (Generation 0)
2) Intermediate objects (Generation 1)
3) Oldest objects (Generation 2)

Memory cleaning happens in 2 ways:

1) Automatic memory cleanup
2) Manual/Forced memory cleanup

#1 is indeterminate, we never know when this is going to happen. One thing for sure, this happens as soon as there is low disk space is encountered but this is extreme case. In normal cases, this depends on the various factors of the machine on which the application is running.

#2 depends on the code which developer writes, where to force the cleanup.



No comments:

Post a Comment