Feel like a geek and get yourself Ema Personal Wiki for Android and Windows

22 January 2010

Memory leaks with WPF windows

WPF is like an Escher drawing. You should always close the window. Even if you ... did not open it!

If you create a new WPF (XAML) Window object, and do not show it for some reason, you still have to close it or it will stick in you memory until the end of days.
  • In VS2008, create a New WPF application
  • In Window1, create new Button
  • in the Click handler of the Button, put the following statement:
    var w = new Window1();
  • F5, click on the button
  • Close the application: now it won't close because the Window1 instance that was created in the click handler is still somewhere in memory
  • Now change the click handler and Close the window you did not open:
    var w = new Window1();
  • F5 and click and close: now the application will function normally

This seems very odd to me. Moreover, if there is some cleanup required, the Window class should implement the IDisposable interface.