
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Obtaining a Safer File Handle
|
1011
The SafeFileHandle constructor takes two arguments. The first is an IntPtr that con-
tains a handle to an unmanaged resource. The second argument is a Boolean value,
where
true indicates that the handle will always be released during finalization and
false indicates that the safeguards that force the handle to be released during final-
ization are turned off. Unless you have an extremely good reason to turn off these
safeguards, it is recommended that you always set this Boolean value to
true.
Discussion
A SafeFileHandle object contains a single handle to an unmanaged file resource. This
class has two major benefits over using an
IntPtr to store a handle—critical finaliza-
tion and prevention of handle recycling attacks. The
SafeFileHandle is seen by the
garbage collector as a critical finalizer, due to the fact that one of the SafeFileHandle’s
base classes is
CriticalFinalizerObject. The garbage collector separates finalizers
into two categories: critical and noncritical. The noncritical finalizers are run first,
followed by the critical finalizers. If a
FileStream’s finalizer flushes any data, it can
assume that the
SafeFileHandle object is still valid, because the SafeFileHandle final-
izer is guaranteed to run after the
FileStream’s.
The Close method on ...