Dispose and Close Methods
Implementing a finalizer gives your type an opportunity to release any external unmanaged resources (such as database connections or file handles) that it may be holding onto. From the perspective of the users of your type, this makes the resource management implicit: they interact with your type, and your type interacts with the resource as needed. However, since GC happens asynchronously and there are no guarantees as to exactly when the finalizers will be called, this level of control may not be sufficient. In these cases, it is good practice to also offer clients explicit resource management controls.
To provide explicit resource management to clients of your type, implement
the IDisposable
interface. This offers clients a Dispose()
method
they can call to explicitly instruct you to release resources. For types
in which Dispose()
doesn’t
make sense, provide an explicit Close()
method that optionally
forwards to a private implementation of IDisposable.Dispose
.
If your type also has a finalizer (via a C# destructor), your Dispose()
or Close()
implementation
should include a special call to the static SuppressFinalize()
method
on the System.GC
type to indicate that the destructor no
longer needs to be called. Typically, the real finalizer is written to call
the Dispose
/Close
method, as follows:
using System; public class Worker : IDisposable { int id; public Worker(int id) { this.id = id; } // ... protected virtual void Dispose(bool disposing) { if (disposing) ...
Get C# in a Nutshell now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.