The whole idea of IDisposable is that implemented classes will do whatever is necessary for a "smart" cleanup if the IDisposable.Dispose method is called. The exact action performed by Dispose may vary depending on the state of the object and may not always be the desired cleaning style. For example, a command / transaction object can roll back if it is located without first invoking the commit method. This will return the command / transaction to a “safe” state, but not necessarily what was intended.
Please also note that error handling can be different in cases involving an explicit “closure”, deterministic “disposition” or non-deterministic “finalization” (as a result of an object failure). It is semantically clear that a “closed” operation that does not result in a closed object in the correct state should throw an exception. It is less clear that the Dispose method should do this. (*) Some classes will be thrown out of a failed order, while others will not. If an object is abandoned and a problem occurs during finalization, several classes will provide any notification, since there is no good mechanism for solving it. If the “close” operation at the end of saving a document fails because someone pulled out their USB drive too quickly, the application may inform the user that the document may not have been saved, and the user may act accordingly. If the application refuses the file object, therefore, the “close” operation will not occur until some time later, for whatever reason, the USB drive was deleted, in fact, the application cannot cope with this error. In the previous situation, the program could assume that the user will try to save the document again, but in the last situation the document may disappear.
(*) If there is no pending exception in the Dispose case, and Dispose cannot perform the required cleanup, it is pretty clear that an exception needs to be thrown. On the other hand, if an exception is already expected, then a reset from Dispose will destroy all information, except for the previous exception. My preferred style would be to use the Dispose (Exception Ex) method, which will throw Ex as an internal exception if Dispose fails, but without language support this thing can only be supported with inconvenient syntax in vb.net and with questionable behavior in C #.
supercat
source share