Content deleted Content added
Added hatnote |
No edit summary |
||
Line 1:
{{Unreferenced|date=May 2009}}
{{redirect|Dispose||Disposal (disambiguation)}}
In [[computer programming]], the '''dispose pattern''' is a [[design pattern (computer science)|design pattern]] which is used to handle resource cleanup in [[runtime environment]]s that use [[automatic garbage collection]]. The fundamental problem that the dispose pattern aims to solve is that, because objects in a garbage-collected environment have [[finalizer]]s rather than [[destructor (computer science)|destructors]], there is no guarantee that an object will be destroyed at any deterministic point in time—a guarantee that is necessary for some other resource management patterns, such as [[Resource Acquisition Is Initialization]]. The dispose pattern works around this by giving an object a [[method (computer science)|method]] (usually called <code>Dispose()</code> or something similar) which frees any resources the object is holding onto.
== Examples ==
Line 20:
</source>
The <code>try...finally</code> construct is necessary for proper [[exception safety]]—if the code that uses the resource throws an exception, the resource will not be freed unless the <code>Dispose()</code> call is in a <code>finally</code> block. Also, the check against <code>null</code> is necessary if the object representing the resource is not directly instantiated, but rather is obtained from some other source that could return <code>null</code>.
To make this pattern less verbose, several languages have some kind of built-in support for it. For example, [[C Sharp (programming language)|C#]] features the <code>using</code> statement, which automatically and safely calls the <code>Dispose()</code> method on an object that implements the <code>IDisposable</code> [[interface (computer science)|interface]]: <source lang="csharp">
using (Resource resource =
// Perform actions with the resource.
...
|