Wednesday, August 10, 2005

weak reference hell

One of my pet peeves about c# has to do with delegates and events. While they are absolutely wonderful, they also present some challenges. Recently, I was tasked with cleaning up the numerous memory leaks in one of our enterprise applications.

I made the initial pass through cleaning up GUI resources (first place to look) then I started into memory leakage. Bottom line was that we had a LOT.

One of the primary sources for this problem was weak reference events. Basically when you subscribe to an event but don't unsubscribe from the event from an object that stays in memory, then you basically keep that object in memory forever (or until the parent object goes away).

The real kicker though is that there is no easy way to unsubscribe from the event. The only way to unsubscribe is to keep a reference to the original event handler instance that you created when you subscribed.

for instance, say ParentObject wants to subscribe to the KeyPress event of ChildObject. Parent object must have

private KeyPressEventHandler _KeyPressEventHandler;


you subscribe to the event here

_KeyPressEventHandler = new KeyPressEventHandler(tb_KeyPress);
control.KeyPress += _KeyPressEventHandler;


to unsubscribe to the event you do this

control.KeyPress -= _KeyPressEventHandler;

without the unsubscribe, the ChildObject will never exit memory.

now as common as this is and the amount of trouble you have to go through to fix this it would have been nice if the original designers of .net languages would have allows us to simply -= from the event without having to store the signature of the call in the first place.

Weak references are probably the #1 problem of memory leaks in .net.

No comments: