How to leak memory with a single handler..

Posted by Rishi on 29-Jul-09 1:00 PM - Comments (0)

Above is a simple Silverlight 3 application that demonstrates the usefulness of weak events in avoiding memory-leak issues. To demonstrate, I've made use of weak event handler wrappers I introduced in my previous post (the code can also found there). The application itself is very simple, it shows the current memory consumption, allows creation of two types of child windows and enables garbage collection on demand. The two types of child windows by design consume more than a million bytes of memory each (per instance), and both windows basically link up with the root visual's size changed event - with a call like:

   1: // Normal Child Window
   2: ((MainPage)App.Current.RootVisual).SizeChanged +=
   3:         new SizeChangedEventHandler(WeakEventChildWindow_SizeChanged);

However the Weak Event Child Window, makes the following call:

   1: // Weak Event Child Window
   2: ((MainPage)App.Current.RootVisual).SizeChanged +=
   3:       new WeakHandler<SizeChangedEventArgs, SizeChangedEventHandler>(WeakEventChildWindow_SizeChanged);

And that's the only difference between the two. Also, neither of the two handlers are unregistered on closing of the child windows (as they should). But with the weak event window, the memory is reclaimed back when the window is closed (to try open some weak event windows and then give the collect garbage hyperlink couple of clicks), whereas each and every instance of the normal window would persist in the memory until the application is closed/unloaded. The weak event child window can get by, because the event handler doesn't store a strong reference to the child window, rather it holds a weak reference which disconnects the child window's lifetime from the event sources.

Now, even though this a very contrived/simple example, it does show how a casual use of a handler can cause serious memory leaks issues (especially when they are spread out all over the place, with small amounts of leaks). On the flip side, the basic principle for correcting this is that if your event source is going to outlast the event listener's life span, then make sure the event handling is disposable/disposed with the listener closing.

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading