Skip to content

Commit

Permalink
Removing fields.
Browse files Browse the repository at this point in the history
  • Loading branch information
Psichorex committed Jan 29, 2024
1 parent 2ea164f commit f7697fe
Showing 1 changed file with 5 additions and 8 deletions.
13 changes: 5 additions & 8 deletions Lombiq.NodeJs.Extensions/CustomExecTasks/SharedMutex.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,38 +6,35 @@ namespace Lombiq.NodeJs.Extensions.CustomExecTasks;

public class SharedMutex(string mutexName, TimeSpan timeout)
{
private readonly string _mutexName = mutexName;
private readonly TimeSpan _timeout = timeout;

public int RetryIntervalMs { get; set; } = 100;

public bool Execute(
Func<bool> functionToExecute, Action<string, object[]> logWait = null, Action<string, object[]> logError = null)
{
var count = 1;
var stopwatch = Stopwatch.StartNew();
while (stopwatch.Elapsed <= _timeout)
while (stopwatch.Elapsed <= timeout)
{
using (var mutex = new Mutex(initiallyOwned: false, _mutexName))
using (var mutex = new Mutex(initiallyOwned: false, mutexName))
{
if (mutex.WaitOne(0))
{
// Release the mutex asap because we don't need it for execution. We only needed it to verify that
// it is currently not "locked", i.e. in exclusive usage.
mutex.ReleaseMutex();

logWait?.Invoke("Acquired shared access to {0} in {1}.", [_mutexName, stopwatch.Elapsed]);
logWait?.Invoke("Acquired shared access to {0} in {1}.", [mutexName, stopwatch.Elapsed]);

return functionToExecute();
}
}

logWait?.Invoke("#{0} Waiting for shared access to {1}.", [count++, _mutexName]);
logWait?.Invoke("#{0} Waiting for shared access to {1}.", [count++, mutexName]);

Thread.Sleep(RetryIntervalMs);
}

logError?.Invoke("Failed to acquire {0} in {1}.", [_mutexName, _timeout]);
logError?.Invoke("Failed to acquire {0} in {1}.", [mutexName, timeout]);
return false;
}
}

0 comments on commit f7697fe

Please sign in to comment.