Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A Winform program so simple -- but may I have my memory back?

I decided to do a simple Windows Form project with .NET 2.0 in C# to test and see what exactly is causing what seems to be 'growing memory leaks' in my other main UI application.

What I did in this simple project was create two forms: Form1 & Form2

Form1 has one big button that pops up a new instance of Form2.

private void button1_Click(object sender, EventArgs e)
{
    Form2 fm2 = new Form2();
    fm2.ShowDialog();
    fm2.Dispose();
}

And Form2 does nothing, except show itself, until the user decides to close the window.

Now when I start the application and I press the button on Form1, I get a jump in memory usage of about 100~kb. I would close the pop-up, press the button again, and see another 100~kb increment. I would do about 10-20 iterations of this. In the end, I would see a jump from 6,880 KB -> 8,684 KB in the task manager. Now, it would eventually stop at a certain number (8684 KB in this case). After it reaches this, it would no longer increase.

Here is my problem:

My main UI application is obviously a lot more complex than this and if anything, this type of memory increase most likely only accounts for a portion of the overall memory increases I'm seeing. Nonetheless, it's still noticeable, and in a project with many forms, this would look very bad in the task manager, because it looks like a memory leak.

So first of all, is this a memory leak?

Secondly, even if it wasn't, is there any way to prevent this?

like image 299
ykay Avatar asked Dec 04 '25 18:12

ykay


2 Answers

Don't be so concerned about what things "look like". .NET manages memory very well, and if it's not collecting it, it just means you have plenty of free memory available, so why should it bother? Memory is there to be used, not hoarded and kept free.

This is not an issue, and it will take care of itself when it needs to.

like image 166
Erik Funkenbusch Avatar answered Dec 06 '25 07:12

Erik Funkenbusch


The code to show your fm2 form is fine and there is no memory leak.

So first of all, is this a memory leak?

No, it is not. This is how .NET handles managed code. It loads objects in memory and release them when it decides to do so. They may stay in memory even when your program does not need them, until the garbage collector decides to remove them.

Secondly, even if it wasn't, is there any way to prevent this?

In general NO. Using GC.Collect you might notice some MBs of decrement especially when you are dealing with objects that need many MBytes, like images for example, but that does not mean that all resources are released from memory. NET decides that.

like image 33
Yiannis Mpourkelis Avatar answered Dec 06 '25 08:12

Yiannis Mpourkelis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!