Finalizers and SafeHandle

A finalizer

A member written ~ClassName() is a finalizer, not a destructor: it runs before the collector frees the object, at a moment the program does not choose, on a thread of the finalizer queue. It exists so that an object holding an unmanaged handle releases it even when nobody called Dispose.

Create(); Console.WriteLine("before collect"); GC.Collect(); GC.WaitForPendingFinalizers(); Console.WriteLine("after finalizers"); static void Create() { var resource = new Finalizable("first"); resource.Use(); } class Finalizable(string name) { public void Use() => Console.WriteLine($"using {name}"); ~Finalizable() => Console.WriteLine($"finalized {name}"); }

dotnet run

using first
before collect
finalized first
after finalizers

finalized first printed after the collection, between the two lines of the main method: the collection found the object unreachable, queued it, and the wait let the queue drain. Without the WaitForPendingFinalizers call the line could appear later, or not at all if the process ended first.

GC.WaitForPendingFinalizers

Dispose and SuppressFinalize

A type with both a finalizer and Dispose must tell the runtime that the cleanup already happened, or the work runs twice. GC.SuppressFinalize(this) is that call:

using (var disposed = new Tracked("disposed")) { disposed.Use(); } Create("finalized"); GC.Collect(); GC.WaitForPendingFinalizers(); Console.WriteLine("done"); static void Create(string name) { var resource = new Tracked(name); resource.Use(); } class Tracked(string name) : IDisposable { private bool disposed; public void Use() => Console.WriteLine($"using {name}"); public void Dispose() { if (disposed) { return; } disposed = true; Console.WriteLine($"disposed {name}"); GC.SuppressFinalize(this); } ~Tracked() => Console.WriteLine($"finalized {name}"); }

dotnet run

using disposed
disposed disposed
using finalized
finalized finalized
done

The first object was disposed and its finalizer was suppressed, so only disposed disposed printed. The second was dropped without a Dispose call, and the finalizer did the release, one collection later. The flag makes a second Dispose harmless, which a caller may always do.

SafeHandle

The BCL ships the pattern ready-made: SafeHandle owns one handle, releases it exactly once, and works with using like any other disposable. A user type derives from SafeHandleZeroOrMinusOneIsInvalid and writes only the release:

using Microsoft.Win32.SafeHandles; var handle = new MyHandle(); Console.WriteLine($"closed before {handle.IsClosed}"); using (handle) { Console.WriteLine("in block"); } Console.WriteLine($"closed after {handle.IsClosed}"); Console.WriteLine("done"); class MyHandle : SafeHandleZeroOrMinusOneIsInvalid { public MyHandle() : base(true) { } protected override bool ReleaseHandle() => true; }

dotnet run

closed before False
in block
closed after True
done

The true passed to the base constructor means "this handle owns its resource", so the base class runs the release on disposal and from its own finalizer if the object is never disposed. That is the shape a P/Invoke wrapper should have, and the interop lesson later uses it for a libc handle.

Exercises

  1. Remove GC.SuppressFinalize from Tracked.Dispose and count the cleanup lines.
  2. Remove the disposed flag and call Dispose twice.
  3. Give MyHandle a name it prints in ReleaseHandle and watch when the release runs.
  4. Write the same Tracked class with the full Dispose pattern, protected virtual void Dispose(bool) and a sealed subclass.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. When does a finalizer run?

    Answer

    After a collection finds the object unreachable, on the finalizer thread

    The collector queues the object and the finalizer thread runs the method later.

  2. Why is a finalizer not a destructor?

    Answer

    It does not run at a defined time and the memory is freed later

    C# has no deterministic destruction; the finalizer is a safety net, not a scope end.

  3. What does this program print? var w = new W("a"); GC.Collect(); GC.WaitForPendingFinalizers(); class W(string n) { ~W() => Console.WriteLine("f " + n); }

    Answer

    f a

    The local is not used again, so the collection treats it as unreachable and the finalizer runs.

  4. What does GC.SuppressFinalize(this) do?

    Answer

    Stops the finalizer from running after a successful Dispose

    The cleanup already happened, so the finalizer would only repeat it.

  5. How many collections does a finalizable object survive after it becomes unreachable?

    Answer

    One, then the second frees it

    The first collection queues it for the finalizer, and the memory is reclaimed later.

  6. What does this program print? using (var t = new T()) { Console.WriteLine("body"); } class T : IDisposable { public void Dispose() => Console.WriteLine("dispose"); ~T() => Console.WriteLine("finalize"); }

    Answer

    body and then dispose

    The program ends before a collection, so the finalizer is not guaranteed to print.

  7. Why must a finalizer be short?

    Answer

    It runs on one thread for the whole process and an exception in it is fatal

    A slow or throwing finalizer holds the queue and can take the process down.

  8. What does the bool in SafeHandleZeroOrMinusOneIsInvalid(true) mean?

    Answer

    This handle owns its resource and releases it on dispose and in its finalizer

    The base class uses it to decide whether it must release the handle itself.

  9. What does this program print? var h = new H(); Console.WriteLine(h.IsClosed); h.Dispose(); Console.WriteLine(h.IsClosed); class H : Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid { public H() : base(true) { } protected override bool ReleaseHandle() => true; }

    Answer

    False and then True

    Dispose closes the handle, and IsClosed reports the state afterwards.

  10. Which type should a new P/Invoke wrapper own its handle with?

    Answer

    A SafeHandle subclass

    SafeHandle already handles the release-once rule, the finalizer and the disposal.

The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image