Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unregistered event handlers cause memory leak

I'm maintaining a web application that has a memory leak.

Based on my investigation using Red Gate ANTS memory profiler I'm pretty sure that the memory leak is caused by event handlers in the business layer.

There's a collection that registers an event handler on each item that's added so that the collection can re-sort when the item's date is changed. It appears that this event handler is the culprit.

The business layer for this application is quite complicated, so keeping the collection and its items in memory drags a bunch of other objects with it.

I've implemented IDisposable on the collection and removed the event handlers in the Dispose method:

p.OnPunchDateChanged -= this.OnPunchDateChanged;

However, implementing IDisposable doesn't help since I can't wrap all the references to the collection in using or try/catch blocks. This collection is used by portions of the application that I don't have control over.

How can I clear these event handlers to resolve this memory leak?

like image 527
Joseph Anderson Avatar asked Jan 15 '09 19:01

Joseph Anderson


People also ask

What is the main cause of memory leaks?

DEFINITION A memory leak is the gradual deterioration of system performance that occurs over time as the result of the fragmentation of a computer's RAM due to poorly designed or programmed applications that fail to free up memory segments when they are no longer needed.

How did you avoid memory leaks in C#?

If you have implemented a very long-running or infinite running thread that is not doing anything and it holds on to objects, you can cause a memory leak as these objects will never be collected. The fix for this is to be very careful with long-running threads and not hold on to objects not needed.

What is a memory leak vulnerability?

Description. A memory leak is an unintentional form of memory consumption whereby the developer fails to free an allocated block of memory when no longer needed. The consequences of such an issue depend on the application itself.


1 Answers

First off, just to prove the point, try logging the adding and removal of events to a simple text file. Then, check how many were added vs removed.

It sounds as if there is a bug somewhere in the business logic which is not unregistering the event in all circumstances.

like image 67
Simon Hughes Avatar answered Oct 07 '22 22:10

Simon Hughes