See Also: SafeHandle Members
The System.Runtime.InteropServices.SafeHandle class provides critical finalization of handle resources, preventing handles from being reclaimed prematurely by garbage collection and from being recycled by Windows to reference unintended unmanaged objects. Before the .NET Framework version 2.0, all operating system handles could only be encapsulated in the IntPtr managed wrapper object.
The System.Runtime.InteropServices.SafeHandle class contains a finalizer that ensures that the handle is closed and is guaranteed to run, even during unexpected AppDomain unloads when a host may not trust the consistency of the state of the AppDomain.
This class is abstract because you cannot create a generic handle. To implement System.Runtime.InteropServices.SafeHandle, you must create a derived class. To create System.Runtime.InteropServices.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 System.Runtime.InteropServices.SafeHandle for each operating system handle type; such as MySafeRegistryHandle, MySafeFileHandle, and MySpecialSafeFileHandle. Some of these derived classes are prewritten and provided for you in the Microsoft.Win32.SafeHandles namespace.
Writing your own classes derived from System.Runtime.InteropServices.SafeHandle is an advanced programming feature. A set of prewritten classes derived from System.Runtime.InteropServices.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.