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(handle); return handle; } public static void DestroyDb(IntPtr handle) { Trace("Destroying Db", handle); ValidHandles.Remove(handle); // Cleaning up the resources associated with the handle. } public static void UseDb(IntPtr handle) { Trace("Starting using Db", handle); // Just mimic some extra work a method might do. PerformLongRunningPrerequisite(); // Using the handle Trace("Using Db", handle); PInvokeIntoDb(handle); } private static void PInvokeIntoDb(IntPtr handle) {} private static void Trace(string message, IntPtr handle) { Console.WriteLine( $"{message}. Id: {handle}, IsValid: {IsValid(handle)}."); } public static bool IsValid(IntPtr handle) => ValidHandles.Contains(handle); private static void PerformLongRunningPrerequisite() { // Skipped for now. } } We don’t want to use native resource directly, so we’ll create a wrapper - RocksDbWrapper: public class RocksDbWrapper : IDisposable { private IntPtr _handle = RocksDbNative.CreateDb(); public void Dispose() => Dispose(true); public void UseRocksDb...
First seen: 2025-03-31 05:40
Last seen: 2025-03-31 11:42