This is a mirror of official site: http://jasper-net.blogspot.com/

Investigating .NET Memory Management and Garbage Collection

| Thursday, March 25, 2010
We will be looking into the world of managed memory In this article. It is a world in that part of the CLR where the garbage collector is king.  We will consider what a memory leak is, how the garbage collector works and why it cannot always free memory;  we will then, finally and most excitingly, reveal how to examine both memory and specific objects using Son of Strike (SOS).
What is a memory leak?

At its most basic, a memory leak happens when memory has been allocated and, for whatever reason, that memory is not freed when the application has finished using it.  In a .Net language, you allocate memory by creating an object and you free the memory by allowing the reference to that object to go out of scope.  Simply put:

void MethodName()
{

Object o = new Object();

//Create a new Object and store a reference to it as o
DoSomethingWith(o); 

//Use the new Object by passing the reference to o
o = null;           

//Lose the reference to the new Object, it is now eligible for freeing

}                                      

//o is now out of scope so can be freed

When “o” goes out of scope, the garbage collector can examine the object to see if it has any references; if nothing is referencing the object, it can be freed.  If the “DoSomethingWith” method caused a reference to be kept to “o” then, when the garbage collector checked to see if it was being used, there would still be a reference and so it would not be able to free the memory.

Read more: simple-talk

Posted via email from jasper22's posterous

0 comments: