Reputation: 135
I'm kinda new to C#. I read that closing a form instead of hiding can free memory. However, when I closed a form, it even made memory increases. To be specific, I have two form: Form1
and Form2
. When I log in user successfully, Form2
will open (Memory is 20Mb). Form2
have a button to log out user, close it and turn back to Form1
(Memory now increases to 41Mb and continue increasing for the next user). I don't know why, is there anybody can help me? This is my code to close
Form2:
private void doctorLogoutBtn_Click(object sender, EventArgs e)
{
imgBox.Image.Dispose();
this.Dispose();
Form1 Login = new Form1();
Login.Show();
this.Close();
}
Upvotes: 0
Views: 291
Reputation: 186678
It should be something like this:
using System.Linq;
...
private void doctorLogoutBtn_Click(object sender, EventArgs e)
{
// Free image resources (may appear to be optional, but doesn't spoil anything)
imgBox.Image.Dispose();
// Do we have any Form1 instances?
Form1 Login = Application
.OpenForms
.OfType<Form1>()
.LastOrDefault(); // If we have several Form1's, let's take the last one
// Only when we haven't any Form1 instances we have to create a new one
if (null == Login)
Login = new Form1();
Login.Show();
// Close (and Dispose)
this.Close();
}
In your current code
...
Form1 Login = new Form1();
Login.Show();
...
you are creating yet another Form1
instance while not looking for alreday created ones.
Upvotes: 1
Reputation: 4153
Well from your description you want to go back to Form1
that was already created but what I can see from this short piece of code you create a new Form.
Form1 Login = new Form1();
Is the old Form1
released when you are displaying Form2
? Maybe the old one is not properly released? The discolosed part fo code doesn't tell that.
it's too little code that you show to be sure but you can run a Memory profiler (dotMemory, ANTS Memory) and check if there are some objects left that should not be.
Upvotes: 1