0

I have a test WPF application that has two windows (I'm also using MVC and not MVVM). Both which have one button that should direct the user to the other window.

Initially, I tried this code (I'm only showing the event handlers):

MainWindow.xaml.cs

private static void Button_Click(object sender, RoutedEventArgs e)
{
    OtherWindow k = new OtherWindow();
    k.Show();
    this.Close();
}

OtherWindow.xaml.cs

private static void Button_Click(object sender, RoutedEventArgs e)
{
    MainWindow k = new MainWindow();
    k.Show();
    this.Close();
}

The code works, but I take a look at the memory usage and it increases every time I switch window. Is this normal or is there a way to avoid this and keep the simplicity?

Kookie
  • 328
  • 4
  • 14
  • Creating a window is definitely expensive, than staying inside an already created window. May be you can explore more on Navigation Services in WPF. – Siva Gopal Oct 01 '18 at 10:57

1 Answers1

0

It's very easy to run into memory leaks in WPF, especially when instantiating and disposing of windows multiple times.

I'd recommend taking a look at this page:

http://svetoslavsavov.blogspot.com/2010/05/memory-leaks-in-wpf-applications.html

which details the most common ways to run into a memory leak in WPF and how to fix it.

I'd suggest looking at the Event Handlers and Events from Static Objects sections first.

It seems that you aren't removing your event handlers for your window before closing it, which means that the Window will be kept in memory.

You should also take a look at this thread for good points on disposing of resources correctly. Check out the answer by rookie1024: What is the correct way to dispose of a WPF window?

akseli
  • 1,416
  • 14
  • 22