Finalizers are tricker than you might think. Part 2
Published on: 2025-05-20 19:58:00
In the previous part we discussed why the finalizers should only deal with unmanaged resources and in this post I want to show that this is not as simple as it sounds.
Let’s reiterate again what a native resource is. Native resource is a resource that is not managed by the CLR. Such resource is typically handled by native code and is exposed via the following API:
a “constructor” that allocates the resource and returns a handle to it
a “destructor” that cleans the resource up and
a set of methods that take a handle to perform an operation
For example, RocksDb is a well-known key-value store written in C++ with C-bindings that allow non-C++ application to consume it via an interoperable API. Here is a naive example of such API.
public static class RocksDbNative { private static readonly HashSet < IntPtr > ValidHandles = new (); public static IntPtr CreateDb () { // Allocating native resource used by the DB. IntPtr handle = 42 ; Trace ( "Creating Db" , handle ); ValidHandles . Add
... Read full article.