Dispose pattern: Difference between revisions

Content deleted Content added
Problems: Init, give balanced view of problems
typo "aris" to "arise"
Line 140:
 
== Problems ==
Beyond the key problem of correct resource management in the presence of returns and exceptions, and heap-based resource management (disposing objects in a different scope from where they are created), there are many further complexities associated with the dispose pattern. These problems are largely avoided by [[RAII]]. However, in common simple use these complexities do not arisarise: acquire a single resource, do something with it, automatically release it.
 
A fundamental problem is that having a resource is no longer a [[class invariant]] (the resource is held from object creation until it is disposed, but the object is still live at this point), so the resource may not be available when the object tries to use it, for example trying to read from a closed file. This means that all methods on the object that use the resource potentially fail, concretely usually by returning an error or raising an exception. In practice this is minor, as use of resources can usually fail for other reasons as well (for example, trying to read past the end of a file), so these methods already might fail, and not having a resource just adds another possible failure. A standard way to implement this is to add a boolean field to the object, called <code>disposed</code>, which is set to true by <code>dispose</code>, and checked by a [[guard clause]] to all methods (that use the resource), raising an exception (such as <code>ObjectDisposedException</code> in .NET) if the object has been disposed.<ref name="msdn_dispose">{{cite web |url=https://msdn.microsoft.com/en-us/library/b1yfkh5e(v=vs.110).aspx |title=Dispose Pattern}}</ref>