
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
210
|
Chapter 3: Classes and Structures
}
// Release any unmanaged objects here...
// Call base class' Dispose method.
base.Dispose(disposeManagedObjs);
}
catch (Exception)
{
hasBeenDisposed = false;
throw;
}
hasBeenDisposed = true;
}
}
}
Whether this class directly contains any references to unmanaged resources, it
should be disposed of as shown in the code.
Discussion
The dispose design pattern allows any unmanaged resources held by an object to be
cleaned up from within the managed environment. This pattern is flexible enough to
allow unmanaged resources held by the disposable object to be cleaned up explicitly
(by calling the
Dispose method) or implicitly (by waiting for the garbage collector to
call the destructor). Finalizers are a safety net to clean up objects when you forget to
do it.
This design pattern should be used on any base class that has derived
types that hold unmanaged resources. This indicates to the inheritor
that this design pattern should be implemented in their derived class
as well.
All the code that needs to be written for a disposable object is written within the
class itself. First, all disposable types must implement the
IDisposable interface. This
interface contains a single method,
Dispose, which accepts no parameters and
returns
void. The Dispose method is overloaded ...