Search code examples
c#.net

SafeHandle in C#


What is SafeHandle? how does it differ from IntPtr? When should I use one? What are its advantages?


Solution

  • I think MSDN is pretty clear in definition:

    The 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 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 SafeHandle, see Safe Handles and Critical Finalization.

    This class is abstract because you cannot create a generic handle. To implement SafeHandle, you must create a derived class. 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; such as MySafeRegistryHandle, MySafeFileHandle, and MySpecialSafeFileHandle. Some of these derived classes are prewritten and provided for you in the Microsoft.Win32.SafeHandles namespace.