1

Have a simple Windows Form with some controls on it. I've been looking for what I believe to be a memory leak. What happens is when I look at the Diagnostic Tools in VS2015, I see the private bytes climb every time I instantiate this form.

So I wrote a little routine that just opens the form a couple hundred times and added a Close() in a timer that already existed in that form. I yanked out all other Event handlers in that form and have narrowed it down to the simplest code to demonstrate the problem.

Here is how I open it...

        for (int x = 0; x < 200; x++)
        {
            new frmShipIt().ShowDialog();
        }

And here is the form class...

    public frmShipIt()
    {
            InitializeComponent();
    }

    private void timerInit_Tick(object sender, EventArgs e)
    {
        timerInit.Enabled = false; //...causes memory leak
        this.Close();
    }

I wont post the Form.Designer code since there are a lot of controls on it.

When I run this - I see the private bytes graph in the VS Diagnostic Tools rise at pretty much a 45 degree angle. If I let it run long enough, it will eventually throw an OutOfMemoryException.

Through trial and error, I comment out the line in the timer event handler that sets Enabled=false and the problem goes away. The private bytes rise to a point - and then level out. Even as the program is showing/closing form objects. I can run it all day with no problem. Which is what I would expect even if I left the offending line in the timer event handler.

So my question is: "WHY?"

BTW - if I just create a new form, add a timer and run this same test I do not see this problem. So it must be something one of the other controls I have on the form is causing - but I don't understand how there can be a relationship between disabling the timer and the other controls.

So I'm looking for suggestions on where to start looking. How does setting Timer.Enabled=false right before I close the form cause the GC to not remove this object from memory?

William Madonna Jr.
  • 242
  • 1
  • 3
  • 12
  • I think the issue is with creating many forms with `ShowDialog` - see [Form.ShowDialog() and dispose](http://stackoverflow.com/questions/11454291/form-showdialog-and-dispose) – stuartd Nov 06 '16 at 14:23
  • Try to `Dispose()` `timerInit` before `this.Close()` after `timerInit.Enabled = false;` and `Dispose()` form itself after `this.Close()` – Thus Spoke Nomad Nov 06 '16 at 14:35

0 Answers0