msigrist
Thu Jan 15 04:17:54 CST 2004
Hi Brad,
I think I can give you an answer precise enough so that you can
formulate your own rule re. when to call IDisposable.Dispose and when
not.
All framework classes that internally use unmanaged resources
implement the IDisposable interface. This means that you CAN (but
don't HAVE TO) explicitly tell the class instance to release the
unmanaged resources once you do not need it any more.
If you decide to call Dispose, there might be some performance or
memory benefits, although they sometimes are so small that they are
almost not measurable. If you decide not to call Dispose, the garbage
collector eventually will call the inherited Finalize method of the
class at least once (usually twice), which will invoke the class'
destructor, which will internally make the Dispose call that you did
not make. However you decide, there will be no destabilizing effects.
Just some extra calls which could be avoided.
However, for some framework classes, it IS extremely important that
their internally managed resources be released ASAP. How do you
recognize such classes? Simple: They always have, in addition to the
Dispose method, a method such as Close that makes it unmistakeably
clear what it is there for. Internally, Close simply calls Dispose.
You can call either one of them. Usually (but not always), Close can
be called only once, whereas Dispose always can be called as often as
you like (it's a common convention).
Conclusion:
Rule no. 1: If there is a method such as Close, ALWAYS make sure it is
called (e.g., enclose it in a "finally" clause).
Rule no. 2: If the class only implements Dispose, but has no method
such as Close, make your own decision. As to myself, I always call
it, because this is never wrong - and, after all, it's just one
statement! However, I do not construct "finally" clauses just to
protect the call to Dispose from any unexpected errors.
Posted Via Usenet.com Premium Usenet Newsgroup Services
----------------------------------------------------------
** SPEED ** RETENTION ** COMPLETION ** ANONYMITY **
----------------------------------------------------------
http://www.usenet.com