Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form.ShowDialog() and dispose

If I have a method like this:

public void Show()
{
   Form1 f = new Form1();
   f.ShowDialog();
}

Do I still need to call dispose on the form even though it will go out of scope, which will be eligible for garbage collection.

From some testing, calling this Show() multiple times .. at some point it seems like the GC collects it since I can see the memory spiking then it goes down at some point in time.

From MSDN it seems to say you MUST call dispose when the form is not needed anymore.

like image 858
pdiddy Avatar asked Jul 12 '12 14:07

pdiddy


People also ask

Does form close call Dispose?

After you close the form by Close or by clicking on X, it will be disposed automatically.

How do I close a ShowDialog form?

When a form is shown using the ShowDialog method, it is necessary to set the form's DialogResult property to close to form. This property can be set using the enum that's also called DialogResult. To close a form, you just need to set the form's DialogResult property (to any value by DialogResult.

What happens after a form that has been displayed with the ShowDialog method is closed by the user?

When a form is displayed as a modal dialog box, clicking the Close button (the button with an X at the upper-right corner of the form) causes the form to be hidden and the DialogResult property to be set to DialogResult. Cancel . Unlike non-modal forms, the Close method is not called by the .

What is the difference between show and ShowDialog?

Show() method shows a windows form in a non-modal state. ShowDialog() method shows a window in a modal state and stops execution of the calling context until a result is returned from the windows form open by the method.


1 Answers

ShowDialog has side effect of keeping the GDI objects alive. In order to avoid GDI leak we need to dispose the ShowDialog appropriately. Where as Show method does not have any implication and GDI will be released appropriately. It is recommended to dispose the showDialog and do not rely on Garbage collector.

like image 55
Mendy Avatar answered Sep 20 '22 11:09

Mendy