System.Runtime.InteropServices.SafeHandle Class

Represents a wrapper class for operating system handles. This class must be inherited.

See Also: SafeHandle Members

Syntax

public abstract class SafeHandle : System.Runtime.ConstrainedExecution.CriticalFinalizerObject, IDisposable

Remarks

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

For more information about the benefits of using a System.Runtime.InteropServices.SafeHandle, see Safe Handles and Critical Finalization.

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.

Note:

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.

Requirements

Namespace: System.Runtime.InteropServices
Assembly: mscorlib (in mscorlib.dll)
Assembly Versions: 2.0.0.0, 4.0.0.0
Since: