skip to content

In C#, when does a disposable type need the Dispose(bool) pattern or a finalizer, and why does SafeHandle usually make the finalizer unnecessary?

level: seniorimportance: should knowfreq 45%

answer

  1. two different reasons, two different pieces
  2. unsealed versus sealed
  3. a raw IntPtr is the trigger
  4. disposing true or false
  5. ReleaseHandle runs once

basics

~20 s

Dispose(bool) is the hook an unsealed disposable class offers its subclasses. A finalizer is needed only by a type directly holding a raw unmanaged handle, and wrapping that handle in a SafeHandle subclass moves the finalizer into SafeHandle.

solid answer

~40 s

The two pieces answer different questions. `protected virtual void Dispose(bool disposing)` exists because a class is **unsealed**: the public `Dispose()` calls `Dispose(true)` then `GC.SuppressFinalize(this)`, and a derived class overrides `Dispose(bool)` and calls `base.Dispose(disposing)`. A **finalizer** exists only because the type directly holds an unmanaged resource such as an `IntPtr` from native code; it calls `Dispose(false)`, and the `false` path may release only that unmanaged resource, never other managed objects, which may already be finalized. The documentation recommends wrapping the handle in a `SafeHandle` subclass instead: you override `IsInvalid` and `ReleaseHandle()`, and `SafeHandle`, which already has a finalizer and derives from `CriticalFinalizerObject`, reference-counts the handle and calls `ReleaseHandle()` at most once, on `Dispose()` or finalization. Your class then holds only a managed object and needs no finalizer.

code

csharp · 41 lines
csharp
using System.Runtime.InteropServices;

using (var buffer = new NativeBuffer(64))
{
    Console.WriteLine($"handle valid: {!buffer.Handle.IsInvalid}");
}

sealed class NativeMemoryHandle : SafeHandle
{
    public NativeMemoryHandle(int size) : base(IntPtr.Zero, ownsHandle: true)
        => SetHandle(Marshal.AllocHGlobal(size));

    public override bool IsInvalid => handle == IntPtr.Zero;

    protected override bool ReleaseHandle()
    {
        Marshal.FreeHGlobal(handle);
        Console.WriteLine("ReleaseHandle: memory freed once");
        return true;
    }
}

class NativeBuffer : IDisposable
{
    private bool _disposed;
    public NativeMemoryHandle Handle { get; }
    public NativeBuffer(int size) => Handle = new NativeMemoryHandle(size);

    public void Dispose()
    {
        Dispose(disposing: true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (_disposed) return;
        if (disposing) Handle.Dispose();
        _disposed = true;
    }
}

go deeper

for a junior

Recall that most classes never need a finalizer and that a raw native handle belongs in a SafeHandle subclass.

for a middle

Explain the disposing flag: true from Dispose(), false from a finalizer, and what each path may touch.

for a senior

Justify SafeHandle over a hand-written finalizer: at-most-once release, reference counting during native calls, critical finalization, no hand-rolled locking.

for a principal

Treat any new finalizer outside a SafeHandle subclass as a design review item that needs a written reason.

## Two pieces, two reasons The full **dispose pattern** in .NET has three parts, and each exists for a separate reason: | Piece | Signature | Exists because | |---|---|---| | Public dispose | `public void Dispose()` | The type implements `IDisposable` | | Extension hook | `protected virtual void Dispose(bool disposing)` | The type is **unsealed**, so subclasses may add cleanup | | Finalizer | `~MyType()` | The type **directly** holds an unmanaged resource | A sealed class wrapping managed disposables needs only the first. An unsealed one adds the second. Only a type that itself stores a raw native handle, typically an `IntPtr` obtained from native code, adds the third, and the documentation calls even that "a highly advanced scenario that can be typically avoided". ## The Dispose(bool) contract In the basic pattern the public method is fixed: ```csharp public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } ``` The `disposing` argument says who is calling: - **`true`** means a caller invoked `Dispose()` deterministically. The method may dispose other managed objects it owns (cascading) and release unmanaged resources. - **`false`** means the call came from a finalizer. Only unmanaged resources may be released, because the order in which objects are finalized is not deterministic and owned managed objects may already be finalized. A derived class overrides `Dispose(bool)`, performs its own cleanup and calls `base.Dispose(disposing)`. It does not re-implement `IDisposable` and does not override the public `Dispose()`; analyzer rule CA1063, "Implement IDisposable correctly", reports those mistakes. The design guidelines also say not to make the parameterless `Dispose` virtual and not to declare other `Dispose` overloads. ## What GC.SuppressFinalize is for `GC.SuppressFinalize(this)` tells the runtime that this object's finalizer no longer needs to run, because `Dispose()` already did the cleanup. If the type has no finalizer, the call has no effect. CA1816 still asks unsealed types to make the call, so that a derived class which adds a finalizer is covered without re-implementing `IDisposable`. It must pass `this`, and it belongs in `Dispose()`, not elsewhere. ## Why a hand-written finalizer is hard Writing finalizer logic correctly is difficult, which is why the docs recommend `SafeHandle` instead: 1. It runs on the runtime's finalizer thread at an unpredictable time, possibly while another thread is still using the handle in a native call. 2. It must not touch other finalizable objects. 3. It must not throw, and it must cope with a half-constructed object if the constructor failed. 4. Disposal racing with finalization or with another `Dispose()` call can free the handle twice unless you add synchronization. ## How SafeHandle removes the finalizer from your class `System.Runtime.InteropServices.SafeHandle` is an abstract class (it derives from `CriticalFinalizerObject` and implements `IDisposable`) that wraps a native handle in its protected `handle` field. A subclass supplies two members: - `public override bool IsInvalid` says which values mean "no handle"; - `protected override bool ReleaseHandle()` frees the handle, for example with `Marshal.FreeHGlobal` or a native close function. In return `SafeHandle` provides the finalizer (`~SafeHandle()` calls `Dispose(false)`), a reference count, and the guarantee that `ReleaseHandle()` is called once and only once, whether the handle is disposed or finalized and even if `Dispose()` races. The interop marshaller adds a reference while a native call is using the handle, so a concurrent `Dispose()` cannot free it mid-call. The constructor's `ownsHandle` argument says whether `ReleaseHandle()` should run at all. Your class now holds a **managed** object, the `SafeHandle`, and disposes it in the `disposing: true` path like any other owned field. If a caller forgets to dispose, `SafeHandle`'s own finalizer still releases the handle. Most .NET APIs that create native resources already hand back a `SafeHandle` subclass, such as `SafeFileHandle` or `SafeWaitHandle`, which is why very few types outside `SafeHandle` subclasses need finalizers. ## Mistakes reviewers catch - A finalizer on a class whose only fields are managed disposables: it adds finalization cost and does nothing useful, because those objects guard themselves. - A derived class that re-implements `IDisposable` or adds its own public `Dispose()` instead of overriding `Dispose(bool)`. - `GC.SuppressFinalize` called with something other than `this`, or from a method other than `Dispose()`, which CA1816 reports. - Cleanup that lets an exception escape the `disposing: false` path, which the design guidelines forbid outside system-critical failures. ## Checklist - Sealed, managed fields only: `Dispose()` alone. - Unsealed: `Dispose()` calling `Dispose(true)` and `GC.SuppressFinalize(this)`, plus `protected virtual Dispose(bool)`. - Raw native handle: a `SafeHandle` subclass, then the rules above; a finalizer of your own only if a `SafeHandle` truly cannot represent the resource.

  • Why must the disposing: false path not call Dispose() on a FileStream field?
    That path runs from a finalizer, and the runtime finalizes unreachable objects in no guaranteed order, so the stream may already have been finalized and its handle released. Touching it can throw or act on a dead resource. The `false` path releases only unmanaged resources the type holds directly; managed objects clean themselves up through their own finalizers.
  • A derived class adds its own SafeHandle field. What does it override?
    Only `protected override void Dispose(bool disposing)`: when `disposing` is `true` it disposes its `SafeHandle`, and in every case it calls `base.Dispose(disposing)` so the base class cleans up too. It neither re-implements `IDisposable` nor adds a finalizer, because the base `Dispose()` already calls `GC.SuppressFinalize(this)` and the handle has its own finalizer.
  • What does the ownsHandle argument of the SafeHandle constructor control?
    Whether `ReleaseHandle()` is ever called. With `ownsHandle: true` the wrapper frees the handle on dispose or finalization. With `false` it only wraps a handle someone else owns, for example one passed in from a native caller, and disposing the wrapper leaves the handle open. It is the handle-level version of the owned-vs-borrowed question.

  • Every IDisposable class should have a finalizer as a safety net
  • Dispose(bool) is needed because the class holds managed disposable fields
  • The finalizer path should dispose the managed fields too
  • GC.SuppressFinalize disposes the object's fields
  • SafeHandle is only for file handles, not other native resources