Click here to Skip to main content
15,066,066 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I create a WPF project and put a button on MainWindow
write this code in click event to open new windows
SecondWindow is an empty windows without any control or code!

C#
private void Button_Click(object sender, RoutedEventArgs e)
{
    SecondWindow s = new SecondWindow();
    s.Show();
}

I used jetbrains dotmemory to check memory leak
I run app till Mainwindow and take snapshot
then click button to create some SecondWindow and close all second windows then take snapshot
both snapshot were taken when just Mainwindow was oppened
why second snapshot uses more memory?
you can check this even by Windows Task Manager

What I have tried:

C#
private void Button_Click(object sender, RoutedEventArgs e)
{
    SecondWindow s = new SecondWindow();
    s.Show();
}
Posted
Updated 27-Jul-21 19:06pm
Comments
Adérito Silva 31-Jul-21 14:13pm
   
Basically, OriginalGriff's answer explains the reason it happens. .NET is a managed platform, meaning memory allocation and cleaning is automatic and developers don't need to manage it manually. What you are witnessing is the allocation of memory not being cleaned up by .NET immediately, which is normal and expected. If memory consumption keeps growing, .NET will eventually clean it — which is called "garbage collection" — and the "wasted" memory will be free again. Cleaning memory impacts performance while doing so, that's why .NET only cleans it when needed.

If you want to test that, try to "consume" a lot of memory by creating new object instances and leave them out of scope (so they are no longer needed). Repeat that thousands of times and see how memory consumption grows. Eventually, you will see a big drop in used memory, which is when the Garbage Collector cleans it. Visual Studio's performance tools display information about the garbage collection in real-time.

1 solution

Because each time you use the new keyword you allocate space on the heap - it uses a bit of memory, even if the form is empty or controls and whatnot.

And objects you create with new exist until they are Disposed - which doesn't happen until either you explicitly call Dispose on them, or the Garbage COllector is kicked in to clean up the memory - which normally happens only when memory is running low.

In short, that's not a memory leak - it is expected behaviour and will "sort itself out" later.
If you really want to clean it all up, then add a handler to the SecondWindow.Closed event, and manually call Dispose on it as part of your main form code. But to be honest, you don't need to do it, or worry about it!
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900