WinForms Dialog Form — Close or Dispose?

前端 未结 2 658
耶瑟儿~
耶瑟儿~ 2020-12-29 08:01

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

相关标签:
2条回答
  • 2020-12-29 09:01

    According to MSDN you need to dispose under two conditions:

    The two conditions when a form is not disposed on Close is when (1) it is part of a multiple-document interface (MDI) application, and the form is not visible; and (2) you have displayed the form using ShowDialog. In these cases, you will need to call Dispose manually to mark all of the form's controls for garbage collection.

    MSDN Form.Close

    Declaring the form in a using statement would be the appropriate way to handle this.

            using (ChangePasswordForm frm = new ChangePasswordForm())
            {
                frm.ShowDialog();
            }
    
    0 讨论(0)
  • 2020-12-29 09:08

    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.

    0 讨论(0)
提交回复
热议问题