Wednesday, April 25, 2012

How throw works in .Net


As we all know, Exception handling plays a very important role in any developer’s life. When talking about exception handling, throw is the first thing, which comes into our mind. Today, we will see, how actually throw works.





The given code catches the exception and just throws it again, without passing any explicit Exception object. 







Now, let’s take another version of this above code:




This given code will create the object of Employee and will catch the exception and from catch block it will throw the catched exception via ex (our Exception class object).




Now question is how these two code snippets are different. For more analysis, let’s open ILDasm and drop your .EXE into it. For the first snippet, we will see something like below:









From this given image, we can see ex (Exception class object) has been defined as local variable using .local, but in the catch block, compiler changes the throw statement into rethrow. It means, instead of changing the original stack trace, compiler is just re-throwing the existing one.

Whereas, if we will look at second snippet:










Here also ex is defined as a local variable, but catch block is bit different here as compared to snippet 1.  In the catch block, compiler is loading data from location 1 (ldloc 1), which is ex (Exception object) and throws that one. And as a result, this ex will not hold all the stack trace raised earlier except the stack trace from this current state.

So, it is clear that ex override the stack trace whereas, just throw statement does not override the stack trace.


Monday, April 23, 2012

Finalize in .Net


We implement the Finalize method to release the unmanaged resources. First let’s see, what is managed and unmanaged resources. Managed ones are those, which we write in .Net languages. But when we write code in any non .Net language like VB 6 or any windows API, we call it as unmanaged. And there are very high chances that we use any win API or any COM component in our application. So, as managed resources are not managed by CLR, we need to handle them at our own. So, once we are done with unmanaged resources, we need to clean them. The cleanup and releasing of unmanaged is done in Finalize(). If your class is not using any unmanaged resources, then you can forget about Finalize(). But problem is, we can’t directly call Finalize(), we do not have control of it. Then who is going to call this. Basically GC calls this.
And one more thing to remember is, there is no Finalize keyword that we will write and implement it. We can define Finalize by defining the Destructor. Destructor is use to clean up unmanaged resourced. When u will put ~ sign in front of class name, it will be treated as destructor. So, when code is compiled, the destructor is going to convert that into Finalize and further garbage collector will add it to the Finalize queue. Let’s take this sample code:

class A    {
       public A()
       { Console.WriteLine("I am in A"); }
       ~A()
       { Console.WriteLine("Destructor of A"); }
   }

   class B : A    {
       public B()
       { Console.WriteLine("I am in B"); }
       ~B()
       { Console.WriteLine("Destructor of B"); }
   }

   class C : B   {
       public C()
       { Console.WriteLine("I am in C"); }
       ~C()
       { Console.WriteLine("Destructor of C"); }
   }

Now using Reflector, we will see, if Destructor, really converted to Finalize:










And WOW, it’s really done. Here we can see that there is nothing like destructor. Basically destructor is overriding the Finalize method.

Hope it helps !!!

Saturday, April 21, 2012

Memory Leak Analysis for .Net application


Memory leaks in .Net applications are always proven to be the nightmare for developers. Many times we get “OutOfMemoryException”, which is nothing but due to memory leak only. There are many reasons, which lead to memory leak situation. For example, sometimes we forget to release unmanaged resources, dispose heavy objects (i.e., drawing objects), even holding reference of managed objects, longer than necessary can also lead to memory leaks.

So, if the application is small, one can analyze the code and figure it out, which object is causing memory leak. But when it comes to a large application, it is not at all possible to figure out manually. In that case, we need some tool, which can help us to figure out the area or object, which is causing memory leak. So, today I surf internet and came up with a tool called .Net Memory Profiler, which can do analysis for us and give us the statistics of all the instances.

Ok, instead of getting more into theory, let’s jump quickly to the demo. I have a windows form application named “MemoryLeakAnalysis”. Now I open memory profiler, which comes up with the below screen. Profiler can be run in two different modes as interactive (normal mode with UI shown below) and non-interactive mode (can only be used for automated testing as part of script. It will not show any window).
Click on ‘Profile application’ and select the exe of your application, as shown below. If require, command line argument can also be provided
On click of next, you can decide the profiling level as Very low, Low, Medium, High, etc. Moving further, you can also decide, whether you want to enable unmanaged resource tracker (collects information about handles, GDI handles, etc), and finally click on start. Clicking on start will launch your application (here my application name is Test Leakage)
In the right hand side, you can see various options as Collect snapshot, Stop profiling, Show real-time data. And just below that, we have ‘Investigate memory leaks’. On clicking of ‘Investigate memory leaks’, you will get the list of major steps, which needs to be taken up, in order to analyze leakage.





















Now the actual investigation starts.
1)     Perform initial operation - Perform the operation you suspect is memory leaking (e.g., open a document, work with it and then close it). Performing an initial operation will make sure that instances that are only created once are not included in the memory leak investigation. In my case, I’ll click on ‘Start Memory Leak’ button and after a while, I’ll click on ‘Stop Memory Leak’
2)     Collect base snapshot - The base snapshot will be used as a reference when looking for unexpected new instances that are created by the operation. Once the snapshot is taken, we will come up with below screen, with some statistics.
















3)     Perform operation again - Again we will perform the operation, which we suspect are leaking memory.    Because, this operation will give us new snapshot for comparison. In my application, I will again click on ‘start Memory Leak’ button:









4)     Collect primary snapshot - The primary snapshot will be used when investigating new instances that might be part of memory leak.
5)     Identify the types with New instances - Instances shown under Overview tab (highlighted one), are the one’s, which are not garbage collected.








6)   Identify the types which are not expected to have New instances - For those instances, we will find that value of New column is 0, which clearly states that that object is already collected by GC.
7)    Investigate root path - Root path can be extremely useful for identifying memory leaks. Shortest path provide information about why instances are not garbage collected. You can use browse buttons to locate a root path that you’d like to investigate further












8)     Determine whether root path instance is part of memory leak - Instance graph and Allocation call stack will provide information about how the instance is used, why it has not been garbage collected, and how it was created. This information can be used to determine, whether instance is part of memory leak or not













9)     Steps from 6 to 8 can be used to analyze another types.

So, by looking at the instance graph and red arrows shown above, will help us the identify, where exactly leak is happening.