Skip to content

Commit

Permalink
Make disposal behave nice
Browse files Browse the repository at this point in the history
This fix was taken from a PR by @mookid8000 submitted to the original codebase: warrenfalk/rocksdb-sharp#77
  • Loading branch information
sondreb committed May 28, 2021
1 parent f6e1ad7 commit 28529ad
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 12 deletions.
46 changes: 35 additions & 11 deletions csharp/src/RocksDb.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, ColumnFamilyHandleInternal> columnFamilies = null)
{
this.Handle = handle;
Expand All @@ -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)
Expand Down Expand Up @@ -190,7 +214,7 @@ public long Get(byte[] key, long keyLength, byte[] buffer, long offset, long len
}
}

public KeyValuePair<byte[],byte[]>[] MultiGet(byte[][] keys, ColumnFamilyHandle[] cf = null, ReadOptions readOptions = null)
public KeyValuePair<byte[], byte[]>[] MultiGet(byte[][] keys, ColumnFamilyHandle[] cf = null, ReadOptions readOptions = null)
{
return Native.Instance.rocksdb_multi_get(Handle, (readOptions ?? DefaultReadOptions).Handle, keys);
}
Expand Down Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion revision
Original file line number Diff line number Diff line change
@@ -1 +1 @@
3
4

0 comments on commit 28529ad

Please sign in to comment.