Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WinForms Dialog Form -- Close or Dispose?

Tags:

winforms

I've inherited some code and wanted to run this modification by you all, my concern is memory management.

Let us say I have a "base" Form with a bunch of buttons that open "dialog" forms. What is the recommended pattern for opening the dialog forms? Currently we display the "dialog" form like so (in the "base" Form code, upon button click):

ChangePasswordForm frm = new ChangePasswordForm();
frm.ShowDialog();

Then close it like so (in the "dialog" form code):

private void bCancel_Click(object sender, EventArgs e)
{
  this.Close();
  //this.Dispose();  <-- this is what I am considering adding.
}

My rationale for adding Dispose is that I am worried if this form is displayed and closed many times that each time a new instance of the form is created and its resources are never really released -- is this correct? Also, if the form has the "close" X in the top right, should I put a Dispose() call in the FormClosed event as well?

Thanks in advance.

like image 660
mikey Avatar asked Nov 10 '11 15:11

mikey


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.

What is form dispose?

This method invokes the Dispose method of each referenced object. Dispose will be called automatically if the form is shown using the Show method. If another method such as ShowDialog is used, or the form is never shown at all, you must call Dispose yourself within your application.

How do I close my WinForms form?

When we need to exit or close opened form then we should use "this. Close( )" method to close the form on some button click event. When we are running a winform application & need to exit or close SUB APPLICATION or CURRENT THREAD then we should use "System. Windows.

Are WinForms obsolete?

Win Form has been used to develop many applications. Because of its high age (born in 2003), WinForm was officially declared dead by Microsoft in 2014. However, Win Form is still alive and well.


1 Answers

I would use a using statement:

  using (var frm = new ChangePasswordForm()) {
      frm.ShowDialog();
  }

Combine this with a DialogResult:

private void bCancel_Click(object sender, EventArgs e)
{
   this.DialogResult = DialogResult.Cancel;
}

Setting the DialogResult, will close the Dialog, and the caller/owner has some feedback.

And you don't have to worry about Close or Dispose.

like image 135
GvS Avatar answered Sep 17 '22 12:09

GvS