Skip to content

Commit

Permalink
Merge pull request #2293 from dev-joshi/Shared_Engine_Remove_Stack
Browse files Browse the repository at this point in the history
Hi @dev-joshi, thanks for your PR!
  • Loading branch information
mbdavid authored Mar 8, 2023
2 parents cd1ae01 + 71c3355 commit 8fc6b7e
Showing 1 changed file with 29 additions and 40 deletions.
69 changes: 29 additions & 40 deletions LiteDB/Client/Shared/SharedEngine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
#if NETFRAMEWORK
using System.Security.AccessControl;
Expand All @@ -17,7 +15,7 @@ public class SharedEngine : ILiteEngine
private readonly EngineSettings _settings;
private readonly Mutex _mutex;
private LiteEngine _engine;
private int _stack = 0;
private bool _transactionRunning = false;

public SharedEngine(EngineSettings settings)
{
Expand Down Expand Up @@ -50,28 +48,24 @@ public SharedEngine(EngineSettings settings)
/// </summary>
private void OpenDatabase()
{
lock (_mutex)
try
{
_stack++;
// Acquire mutex for every call to open DB.
_mutex.WaitOne();
}
catch (AbandonedMutexException) { }

if (_stack == 1)
// Don't create a new engine while a transaction is running.
if (!_transactionRunning && _engine == null)
{
try
{
_engine = new LiteEngine(_settings);
}
catch
{
try
{
_mutex.WaitOne();
}
catch (AbandonedMutexException) { }

try
{
_engine = new LiteEngine(_settings);
}
catch
{
_mutex.ReleaseMutex();
_stack = 0;
throw;
}
_mutex.ReleaseMutex();
throw;
}
}
}
Expand All @@ -81,18 +75,16 @@ private void OpenDatabase()
/// </summary>
private void CloseDatabase()
{
lock (_mutex)
// Don't dispose the engine while a transaction is running.
if (!this._transactionRunning && _engine != null)
{
_stack--;

if (_stack == 0)
{
_engine.Dispose();
_engine = null;

_mutex.ReleaseMutex();
}
// If no transaction pending, dispose the engine.
_engine.Dispose();
_engine = null;
}

// Release Mutex on every call to close DB.
_mutex.ReleaseMutex();
}

#region Transaction Operations
Expand All @@ -103,14 +95,9 @@ public bool BeginTrans()

try
{
var result = _engine.BeginTrans();
this._transactionRunning = _engine.BeginTrans();

if (result == false)
{
_stack--;
}

return result;
return this._transactionRunning;
}
catch
{
Expand All @@ -129,6 +116,7 @@ public bool Commit()
}
finally
{
this._transactionRunning = false;
this.CloseDatabase();
}
}
Expand All @@ -143,6 +131,7 @@ public bool Rollback()
}
finally
{
this._transactionRunning = false;
this.CloseDatabase();
}
}
Expand Down Expand Up @@ -380,7 +369,7 @@ protected virtual void Dispose(bool disposing)
if (_engine != null)
{
_engine.Dispose();

_engine = null;
_mutex.ReleaseMutex();
}
}
Expand Down

0 comments on commit 8fc6b7e

Please sign in to comment.