Skip to content

Commit 28529ad

Browse files
committed
Make disposal behave nice
This fix was taken from a PR by @mookid8000 submitted to the original codebase: warrenfalk/rocksdb-sharp#77
1 parent f6e1ad7 commit 28529ad

File tree

2 files changed

+36
-12
lines changed

2 files changed

+36
-12
lines changed

csharp/src/RocksDb.cs

Lines changed: 35 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ public class RocksDb : IDisposable
2121

2222
public IntPtr Handle { get; protected set; }
2323

24+
private bool disposed;
25+
2426
private RocksDb(IntPtr handle, dynamic optionsReferences, dynamic cfOptionsRefs, Dictionary<string, ColumnFamilyHandleInternal> columnFamilies = null)
2527
{
2628
this.Handle = handle;
@@ -29,22 +31,44 @@ private RocksDb(IntPtr handle, dynamic optionsReferences, dynamic cfOptionsRefs,
2931
this.columnFamilies = columnFamilies;
3032
}
3133

34+
~RocksDb()
35+
{
36+
ReleaseUnmanagedResources();
37+
}
38+
3239
public void Dispose()
3340
{
34-
if (Handle != IntPtr.Zero)
41+
if (disposed) return;
42+
43+
try
44+
{
45+
ReleaseUnmanagedResources();
46+
GC.SuppressFinalize(this);
47+
}
48+
finally
3549
{
36-
var handle = Handle;
37-
Handle = IntPtr.Zero;
50+
disposed = true;
51+
}
52+
}
53+
54+
void ReleaseUnmanagedResources()
55+
{
56+
// curiosity-ai fork did this check around the logic below, we have dropped it, investigate in the future:
57+
//if (Handle != IntPtr.Zero)
58+
//{
59+
// var handle = Handle;
60+
// Handle = IntPtr.Zero;
61+
//}
3862

39-
if (columnFamilies != null)
63+
if (columnFamilies != null)
64+
{
65+
foreach (var cfh in columnFamilies.Values)
4066
{
41-
foreach (var cfh in columnFamilies.Values)
42-
{
43-
cfh.Dispose();
44-
}
67+
cfh.Dispose();
4568
}
46-
Native.Instance.rocksdb_close(handle);
4769
}
70+
71+
Native.Instance.rocksdb_close(Handle);
4872
}
4973

5074
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
190214
}
191215
}
192216

193-
public KeyValuePair<byte[],byte[]>[] MultiGet(byte[][] keys, ColumnFamilyHandle[] cf = null, ReadOptions readOptions = null)
217+
public KeyValuePair<byte[], byte[]>[] MultiGet(byte[][] keys, ColumnFamilyHandle[] cf = null, ReadOptions readOptions = null)
194218
{
195219
return Native.Instance.rocksdb_multi_get(Handle, (readOptions ?? DefaultReadOptions).Handle, keys);
196220
}
@@ -328,7 +352,7 @@ public void DropColumnFamily(string name)
328352
Native.Instance.rocksdb_drop_column_family(Handle, cf.Handle);
329353
columnFamilies.Remove(name);
330354
}
331-
355+
332356
public ColumnFamilyHandle GetDefaultColumnFamily()
333357
{
334358
return GetColumnFamily(ColumnFamilies.DefaultName);

revision

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
3
1+
4

0 commit comments

Comments
 (0)