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
- A finalizable object needs two collections to be freed: the first queues it for the finalizer, the second frees the memory.
- The finalizer queue is a separate thread, so a program that exits does not promise that finalizers ran; a process shutdown gives them a short time.
- GC.WaitForPendingFinalizers() blocks until the queue is empty. It belongs in tests and diagnostics, not in a hot path.
- An exception in a finalizer is fatal to the process and is not catchable by the program that owned the object, which is one more reason to keep a finalizer tiny.
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
- Remove GC.SuppressFinalize from Tracked.Dispose and count the cleanup lines.
- Remove the disposed flag and call Dispose twice.
- Give MyHandle a name it prints in ReleaseHandle and watch when the release runs.
- 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.
-
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.
-
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.
-
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.
-
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.
-
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.
-
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.
-
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.
-
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.
-
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.
-
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