SafeHandle Class

Note: This class is new in the .NET Framework version 2.0.

Represents a wrapper class for operating system handles.

Namespace: System.Runtime.InteropServices
Assembly: mscorlib (in mscorlib.dll)

public abstract class SafeHandle : CriticalFinalizerObject, IDisposable
public abstract class SafeHandle extends CriticalFinalizerObject implements IDisposable
public abstract class SafeHandle extends CriticalFinalizerObject implements IDisposable

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.


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.

The following code example demonstrates how to implement the SafeHandle class.

using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;

namespace SafeHandleExample
    sealed class MySafeHandleSubclass : SafeHandle
        // Called by P/Invoke when returning SafeHandles
        private MySafeHandleSubclass()
            : base(IntPtr.Zero, true)
        // If & only if you need to support user-supplied handles
        internal MySafeHandleSubclass(IntPtr preexistingHandle, bool ownsHandle)
            : base(IntPtr.Zero, ownsHandle)
        // Do not provide a finalizer - SafeHandle's critical finalizer will
        // call ReleaseHandle for you.
        public override bool IsInvalid

            get { return IsClosed || handle == IntPtr.Zero; }
        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        private static extern bool CloseHandle(IntPtr handle);

        protected override bool ReleaseHandle()
            return CloseHandle(handle);
        public static extern MySafeHandleSubclass CreateHandle(int someState);
    class Class1

        static void Main(string[] args)
            bool ownsHandle = true;
            MySafeHandleSubclass s = new MySafeHandleSubclass(IntPtr.Zero, ownsHandle);

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see System Requirements.

.NET Framework

Supported in: 2.0

Community Additions