Dispose in Forms ?

  • Thread starter Thread starter Cybertof
  • Start date Start date
C

Cybertof

Hi !

I thought the GC was doing the job of cleaning ressources....

Do you know why Microsoft is using Dispose in this sample ?

[C#]
public void ShowMyDialogBox()
{
Form2 testDialog = new Form2();

if (testDialog.ShowDialog(this) == DialogResult.OK)
{
// Read the contents of testDialog's TextBox.
this.txtResult.Text = testDialog.TextBox1.Text;
}
else
{
this.txtResult.Text = "Cancelled";
}
testDialog.Dispose();
}


Link :
http://msdn.microsoft.com/library/default.asp?url=/library/en-
us/cpref/html/frlrfSystemWindowsFormsFormClassShowDialogTopic.asp


Regards,
Cybertof.
 
Cybertof said:
I thought the GC was doing the job of cleaning ressources....

GC cleans up managed resources, in its own good time. Unmanaged
resources such as handles should be freed as soon as possible, and
that's what the Dispose pattern is about. Have a look at the
documentation for IDisposable for more information.
 
Cybertof said:
I thought the GC was doing the job of cleaning ressources....
Do you know why Microsoft is using Dispose in this sample ?

The Forms class implements IDisposable, therefore it has a Dispose() that
needs to be called. Also, you will find that VS inserts a Dispose() routine
in your forms like so:

protected override void Dispose( bool disposing )
{
if ( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

If your form contains nested components that need Disposing then you would
do it here.


Also in your example I would've used the form like this, using using:

public void ShowMyDialogBox()
{
using (Form2 testDialog = new Form2())
{
if (testDialog.ShowDialog(this) == DialogResult.OK)
{
// Read the contents of testDialog's TextBox.
this.txtResult.Text = testDialog.TextBox1.Text;
}
else
{
this.txtResult.Text = "Cancelled";
}
}
}


-- Alan
 
Also read the documentation regarding DialogResult property. Modal dialogs
are never really closed, they are just hidden until you call Dispose().

For non modal forms, there is a new KB article coming out that will
highlight the importance of calling Dispose(). I have found memory leaks in
1.0 and 1.1 that require you to call Dispose on the form (at least for MDI
children).

HTH;
Eric Cadwell
http://www.origincontrols.com
 
Back
Top