C# - High memory consumption when calling method

Asked

Viewed 36 times

0

I am working with a Main Form and it has several Panels. In one of them, the "Geral panel" I use to call the instances of new forms and show in it using the following code of the Formcall class:

public void chamaFormulario(Form form)
{            
        Form activeForm = frmMain.ActiveForm;
        foreach (Panel painel in activeForm.Controls )
        {
            if(painel.Name == "panelGeral")
            {
                painel.Controls.Clear();
                if(form != null)
                {
                    form.TopLevel = false;
                    painel.Controls.Add(form);
                    form.Show();
                }
            }
        }            
}

For example, when the program opens I call a Welcome Form as follows:

private void frmMain_Shown(object sender, EventArgs e)
    {
        frmInicio frm = new frmInicio();
        formCall = new FormCall();
        formCall.chamaFormulario(frm);
    }

When I call the form frmClientes and when opening it, it has a "Back" button that aims to return to the welcome screen, which calls the following method:

private void btVoltarClientes_Click(object sender, EventArgs e)
    {
        frmInicio frm = new frmInicio();
        FormCall form = new FormCall();            
        form.chamaFormulario(frm);
    }

But noting the memory consumption in the VS2017 Community diagnostic tool, what was consuming 60MB over to 96MB, and if I open the customer form again and press back again, it goes up to 136MB... And so on and so forth.

What should I do to solve this high memory consumption?

  • This occurs after you click the button a few times?

  • Maniero. Yes! But the Rovann solution I think solved the problem.

1 answer

2


Try while removing the controls from the panel (painel.Controls.Clear();) discard the forms:

painel.ControlRemoved += (ss, ee) => { ee.Control.Dispose(); };
  • Wow, kind of solved the problem. Now it’s consuming around 38~55MB, I tried clicking and clicking several times. That would be the solution even hehe?

  • 1

    yes, you’re putting the forms inside the panel, and when you remove, they’re still attached and in memory... the Dispose will discard them

  • Thank you Rovann. It worked and solved the problem

  • 2

    I gave one more because it solves the problem, but this is tragic, the ideal is to rearquitete so you don’t have to do this anymore.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.