
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
728
|
Chapter 12: Filesystem I/O
Discussion
MultiWriter implements the IDisposable interface, which helps the users remember
to close the files this will create. Ultimately, if the user forgets to call
Close (a thin
wrapper around
Dispose for semantic convenience), the finalizer (~MultiWriter) will
call
Dispose anyway and close the files when the garbage collector finalizes the
instance. Note that in the public
Dispose method, we call the protected Dispose
method, which closes the file streams we created internally and calls the GC.
SuppressFinalize
method. This is an optimization to keep the garbage collector from
having to call our finalizer.
See Also
See the “FileStream Class,” “GC Class,” and “IDisposable Interface” topics in the
MSDN documentation.
{
Dispose(true);
// Prevent refinalizing.
GC.SuppressFinalize(this);
}
protected void Dispose(bool disposing)
{
try
{
// Only close out once.
if(_disposed == false && disposing == true)
{
// Close each stream.
for(int i=0;i<_streams.Length;i++)
{
_streams[i].Close( );
}
// Indicate we have done this already.
_disposed = true;
}
}
catch(IOException ioe)
{
Console.WriteLine(ioe);
}
}
~MultiWriter( )
{
Dispose(false);
}
}
Example 12-10. MultiWriter class (continued)