From 28529adee5a9ade996ab2464a855a185780db501 Mon Sep 17 00:00:00 2001 From: Sondre Date: Fri, 28 May 2021 22:08:30 +0200 Subject: [PATCH] Make disposal behave nice This fix was taken from a PR by @mookid8000 submitted to the original codebase: https://github.com/warrenfalk/rocksdb-sharp/pull/77 --- csharp/src/RocksDb.cs | 46 ++++++++++++++++++++++++++++++++----------- revision | 2 +- 2 files changed, 36 insertions(+), 12 deletions(-) diff --git a/csharp/src/RocksDb.cs b/csharp/src/RocksDb.cs index fe0b4bf..5456b5c 100644 --- a/csharp/src/RocksDb.cs +++ b/csharp/src/RocksDb.cs @@ -21,6 +21,8 @@ public class RocksDb : IDisposable public IntPtr Handle { get; protected set; } + private bool disposed; + private RocksDb(IntPtr handle, dynamic optionsReferences, dynamic cfOptionsRefs, Dictionary columnFamilies = null) { this.Handle = handle; @@ -29,22 +31,44 @@ private RocksDb(IntPtr handle, dynamic optionsReferences, dynamic cfOptionsRefs, this.columnFamilies = columnFamilies; } + ~RocksDb() + { + ReleaseUnmanagedResources(); + } + public void Dispose() { - if (Handle != IntPtr.Zero) + if (disposed) return; + + try + { + ReleaseUnmanagedResources(); + GC.SuppressFinalize(this); + } + finally { - var handle = Handle; - Handle = IntPtr.Zero; + disposed = true; + } + } + + void ReleaseUnmanagedResources() + { + // curiosity-ai fork did this check around the logic below, we have dropped it, investigate in the future: + //if (Handle != IntPtr.Zero) + //{ + // var handle = Handle; + // Handle = IntPtr.Zero; + //} - if (columnFamilies != null) + if (columnFamilies != null) + { + foreach (var cfh in columnFamilies.Values) { - foreach (var cfh in columnFamilies.Values) - { - cfh.Dispose(); - } + cfh.Dispose(); } - Native.Instance.rocksdb_close(handle); } + + Native.Instance.rocksdb_close(Handle); } public static RocksDb Open(OptionsHandle options, string path) @@ -190,7 +214,7 @@ public long Get(byte[] key, long keyLength, byte[] buffer, long offset, long len } } - public KeyValuePair[] MultiGet(byte[][] keys, ColumnFamilyHandle[] cf = null, ReadOptions readOptions = null) + public KeyValuePair[] MultiGet(byte[][] keys, ColumnFamilyHandle[] cf = null, ReadOptions readOptions = null) { return Native.Instance.rocksdb_multi_get(Handle, (readOptions ?? DefaultReadOptions).Handle, keys); } @@ -328,7 +352,7 @@ public void DropColumnFamily(string name) Native.Instance.rocksdb_drop_column_family(Handle, cf.Handle); columnFamilies.Remove(name); } - + public ColumnFamilyHandle GetDefaultColumnFamily() { return GetColumnFamily(ColumnFamilies.DefaultName); diff --git a/revision b/revision index e440e5c..bf0d87a 100644 --- a/revision +++ b/revision @@ -1 +1 @@ -3 \ No newline at end of file +4 \ No newline at end of file