May 24, 2006

The Close and/or Dispose Connundrum

In my opinion "Close() should not call Dispose()". I am not sure what Microsoft's stance is on this. However their views should not always be taken as best. I remember once I wrote some code to store some settings in a Ini file (this was before Xml and config files) and a colleague came and berated me, telling me that the Microsoft standard is that all settings should go in the registry. I thought 'Ini' files were and still are great. The API is simple as is the 'Ini' file format unlike the registry!
Why should Close() not call or implement Dispose(). What if you call Open on the object again? If its been disposed of by the Close() and SuppressFinaliser() was called then you have problems. How will you get the Finaliser back in the Finaliser queue? If you call Dispose() however then you are explicitly saying that all the objects resources should be relinquished this is not the case with Close() where you might want to Open() the object again.
Also, in OO Semantics Close() does not imply that all unmanaged resources will be released. Calling Close() on an object may release 1 or more unmanaged resources but you cannot assume that it releases all of them. In a lazy implementation it may not release any. You should always call Dispose after Close.
Its possible that Open may be called again on an object some time after Close was called but if the object has been disposed of within the previous call to Close then BANG!. I think Paul Wilson's article makes a good case for this. Check this out as well for some other opinions.
In 'Applied Microsoft .NET Framework Programming', Jeffrey Richter 'strongly discourages' the use of Dispose. He says the garbage collector is well written and you should let it do its job.

No comments: