The SafeHandle class provides protection for handle recycling security attacks; it also provides critical finalization of handle resources. This class allows you to pass to unmanaged code a handle to an unmanaged resource (such as an operating system handle) wrapped in a derived class instance. It provides protection against security attacks by recycling handles. An example of handle recycling is an untrusted user of your handle attempting to queue operations against the resource on one thread while closing the handle on another. The untrusted user would do this in the hope that the handle is reused immediately by some unrelated thread in the process, and the in-process operation returns or alters data that is normally inaccessible to the caller. SafeHandle also provides critical finalization: the ReleaseHandle method is run even when the AppDomain is unloaded by the host, or if normal finalizers block or take too long to clean up.
This class is abstract because you cannot create a generic handle. To implement SafeHandle, you must create a derived class for each operating system handle type. To create SafeHandle derived classes, you must know how to create and free an operating system handle. This process is different for different handle types because some use CloseHandle, while others use more specific methods such as UnmapViewOfFile or FindClose. For this reason, you must create a derived class of SafeHandle for each operating system handle type (for example, SafeRegistryHandle, SafeFileHandle, and MySpecialSafeFileHandle). Some of these derived classes are prewritten and provided for you in the Microsoft.Win32.SafeHandles namespace.
Note |
|---|
| Writing your own classes derived from SafeHandle is an advanced programming feature. A set of prewritten classes derived from SafeHandle is provided as abstract derivations, and this set is located in the Microsoft.Win32.SafeHandles namespace. These classes are designed to provide common functionality supporting file and operating system handles. |
Notes to Inheritors
When you inherit from
SafeHandle, you must override the following members:
IsInvalid and
ReleaseHandle.
You should also provide a default constructor that calls the base constructor with a value that represent an invalid handle value, and a Boolean value indicating whether the native handle will be owned by the managed code.