0

I have some pages in my app. When one of my pages is open while loop creates 1000 buttons (for example). After I navigate between pages and back to first page Objects (Buttons) creates it again. I get memory leak. How can I solve this problem?

public sealed partial class BlankPage1 : Page
{
    public BlankPage1()
    {
        this.InitializeComponent();

        int i = 0;
        while(i < 1000)
        {
            Button button = new Button();
            MainStack.Children.Add(button);
            i++;
        }
    }

    private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
    {
        Frame.Navigate(typeof(BlankPage2));
    }
}

}

  • what's the definition and container of `MainStack`? how did you come to the conclusion that it is an actual leak (debugger, diagnostics, tools)? – Cee McSharpface Sep 06 '20 at 11:42
  • MainStack is StackPanel (System.Windows.Controls). How did I come? ~ +20mb of RAM usage every page opening. Garbage collector isn't work. Memory usage persists – Anonim Anonim Sep 06 '20 at 12:09
  • I tryed some temporary solution: I cached a page with `this.NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Enabled;` and added a check when page is loading: `if (SomeClass.ObjectsExist == false)` then `CreateObjects()` `else` //do nothing. Method `CreateObjects` changes `SomeClass.ObjectsExist` to `true`. It is correct? – Anonim Anonim Sep 06 '20 at 12:38

1 Answers1

0

Well, it's no wonder your memory runs full at some point, because every time you open the "BlankPage1" page, the loop is started every time. But the "old" objects are not deleted by the GC.

Try to create the objects in your ViewModel only at the start of your application, then the objects should not be created every time.

If you still need support, let me know.

abo
  • 131
  • 4