IDisposable objects as fields in a Windows Form

  • Thread starter Thread starter Pino
  • Start date Start date
P

Pino

Hi to all.

I have a Windows Form.
I have a field in my form class which implements IDisposable.
When I should call Dispose to that object?
Is correct to call Dispose of all IDisposable objects in the OnClosed method
of the form?

Thanks,

Pino.
 
Are these objects controls ? If so they will be disposed appropriately when
the form closes.

In general, you can only manually dispose of objects you know are not going
to be used again, if somebody else has a reference to a disposed object and
tries to use it will get an exception (if the call uses the disposed
resource).

Note that objects are eventually discarded by the garbage collector when
there are no references to it, the finalizer of objects that contain
unmanaged resources like brush, pen (gdi+ objects), Control, etc will
dispose of these resources (you must do this is you are using unmanaged
resources). Calling Dispose will simply force the freeing of the resources
to be done sooner.

I general, I dispose only of private objects to which nobody keeps a
reference to but myself, this includes GDI+ objects using during paint and
other "short-lived" resources.
 
When the Form instance is Disposed it will automatically dispose of all
instances of controls contained in its own .Controls collection. You will
also notice auto generated code for disposing of objects in the 'components'
auto generated field. If you are adding objects that are not placed in the
..Controls collection or the 'components' collection then you should add code
the Form dispose to dispose of them.

Phil Wright
Follow the startup of my microISV at...
http://componentfactory.blogspot.com
 
Back
Top