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.
After you close the form by Close or by clicking on X, it will be disposed automatically.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With