Disposing of Forms.

  • Thread starter Thread starter AP
  • Start date Start date
A

AP

If I display a form using the ShowDialog method, when the form is closed
should I have to explicitly call dispose on the form in order to ensure it
releases its resources, or should this be handled by the garbage collector
when the method that instantiates and opens the form goes out of scope?

Thanks,

Adam
 
In any way it isn't error to dispose an object even you have a garbage
collector
 
AP,

If you are not going to use the dialog again (you might want to show it
again, and therefore keep it around), you should call Dispose on it. This
will release any resources that it is holding that you don't want to wait
for the GC to dispose of. This can consist of window handles (in this
case), or other unmanaged resources.

Hope this helps.
 
I was under the impression that Dispose would get called automatically by
the garbage collector when the object goes out of scope. Is this not the
case?

Adam
 
Yes. Calling it yourself is a preventative measure and won't cause any
problems.
 
OK let me ask another question. Suppose I create a panel, and then in a
subclassed form pass in that panel to the constructor of the form, keeping a
handle on the panel outside of the form. I then show the form using
ShowDialog and call dispose on the form. I still have a handle on the panel
however. Do I have to call dispose on the panel also? Or will this be called
by the garbage collector when I no longer have a handle on the panel? And if
the garbage collector calls dispose for the panel, why do I have to
explicitly call it for a modal dialog?

Thanks,

Adam
 
AP said:
I was under the impression that Dispose would get called automatically by
the garbage collector when the object goes out of scope. Is this not the
case?

No, it's not. The garbage collector doesn't do anything when the
variable goes out of scope (objects themselves never go out of scope).
At some time after the variable has gone out of scope, the garbage
collector will collect the object if there's nothing else keeping it
alive, but it could be a long time before that happens.
 
I didn't necessarily mean immediately, just that at some point dispose will
be called automatically if there's nothing else keeping it alive, correct?
 
AP said:
I didn't necessarily mean immediately, just that at some point dispose will
be called automatically if there's nothing else keeping it alive, correct?

Correct - as long as the finalizer for the class calls Dispose. (Not
all classes which implement IDisposable have finalizers, or indeed need
them.)
 
Back
Top