Use SafeHandle when wrapping unmanaged resources

suggest change

When writing wrappers for unmanaged resources, subclass SafeHandle rather than implementing IDisposable and a finalizer yourself. Keep the SafeHandle subclass small. It is usually an internal detail of a class that exposes a usable API. If that wrapper is abandoned, the critical finalizer on SafeHandle still releases the unmanaged handle.

using System.Runtime.InteropServices;

class MyHandle : SafeHandle
{
    public override bool IsInvalid => handle == IntPtr.Zero;
    public MyHandle() : base(IntPtr.Zero, true)
    { }

    public MyHandle(int length) : this()
    {
        SetHandle(Marshal.AllocHGlobal(length));
    }

    protected override bool ReleaseHandle()
    {
        Marshal.FreeHGlobal(handle);
        return true;
    }
}

This example only shows the shape of a SafeHandle. AllocHGlobal is an unmanaged allocation. SafeHandle implements IDisposable and registers a critical finalizer. A production wrapper would expose the memory through a separate class and would not allocate it this way.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents