Wednesday, February 13, 2008

Memory leaks in managed code

This was something we ran into in our application used custom GUI components, and well those were rough days…

 

You sometimes hear that a managed language like C# or Java does away with memory leaks, and frees the programmer from having to think about freeing objects from memory. Well this is not especially true for GUI code.

The main reason for this is the use of the Observer pattern. While a good thing in it self, the observer pattern leads to the “Lapsed Listener” anti-pattern. This is when an object A subscribed to an event of object B which is a long living object (for an example a child form subscribing to event in the parent MDI form) goes out of play without unsubscribing to the event on object B (the child form closes but without unsubscribing from the event on the MDI parent).

This would result in object A never being garbage collected until object B is out of business, what’s worse, if object A reference other objects C and D , this will also not get garbage collected as well.

 

This would lead into couple of problems…

1)       Memory usage of the application grows with time.

2)       If the leaked objects includes controls that hold GDI objects (Windows, Pens etc..), eventually you may run out of these.

3)       The unwanted and presumed –dead objects are still capable of receiving events, this may cause crashes.

 

The general solution is to make sure you unsubscribe from parent events in your dispose method (in .Net).

We had to use a tool to monitor memory consumption and then fix them most probably by disposing events and so…The tools we used to monitor memory were Sci-tech Memory profiler and ANTs profiler both of which are not free, but the best tools in the market for this job..

No comments:

Post a Comment