oMatrix
oMatrix

Reputation: 352

C# WinForm Memory Leak

I have a big winform class that calls from a little one like this:

    void login()
    {           
        mainForm f1 = new mainForm();                
        f1.ShowDialog();
    }

The mainForm will take lots of memory after login (I check it in Task Manager). After closing the mainForm, program returns to login form. At this step I check Task Manager again and see that my program has not released the memory that mainForm used. And after some login, my program crashes and shows "Out of Memory" error.

I have to say that I tested f1.Dispose(), f1=null, GC.Collect() and every other methods that I found.

It will only releases the memory when I close the login form (Its the starting class used in Application.Run)

I want to destroy the mainForm instance (f1) and all resources of this form just like when I close the program.

Upvotes: 1

Views: 2704

Answers (3)

Hans Passant
Hans Passant

Reputation: 941218

Not so sure that the OOM has anything to do with the login form. And it is most certainly not the case that closing or disposing a form will reduce memory usage as reported by Taskmgr.exe.

But you are definitely doing it wrong. A dialog is treated differently in Winforms, it doesn't get automatically disposed like a form you display with Show() does. Necessarily so, you want to retrieve whatever the user entered in the dialog after it closes, that will be hazardous when the dialog is disposed. So you have to do it yourself. The proper pattern is:

    using (mainForm f1 = new mainForm()) {
        if (f1.ShowDialog() == DialogResult.Ok) {
            // Retrieve data entered by user and do something with it
            //...
        }
    }

With the using statement ensuring that the dialog instance gets disposed after you retrieved the dialog results.

Upvotes: 3

Peter Wishart
Peter Wishart

Reputation: 12270

Maybe the mainform creates a reference to itself when shown, check any references/delegates/events it assigns and make sure they are unregistered when mainform is done, or move event handlers (i.e. application events) to a separate class.

So far 100% of the time I "found a .NET memory leak", it wasnt! Dispose all disposables, watch what you do with statics that hold references, don't make duplicate event subscriptions and tidy them up when possible.

Use SOS as mouters says to check gcroots on the mainform class after you run dispose it and call GC.Collect(3) a couple of times, once you trace where the references are you should find the bug.

Upvotes: 1

Chris Moutray
Chris Moutray

Reputation: 18349

Couple of thoughts:

Upvotes: 2

Related Questions