Search code examples
c#memoryformclosing

Why does memory increase after closing a form?


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();   
}

Solution

  • 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.