public async Task CheckLocks() { while (true) { if (_nodeStateService.Role == NodeState.Leader) { try { var objectLocks = _stateMachine.GetLocks(); List <Lock> expiredLocks = new List <Lock>(); foreach (var clusterLock in objectLocks) { if (clusterLock.Value.IsExpired()) { _logger.LogDebug("Detected that lock for object " + clusterLock.Key + " is expired."); expiredLocks.Add(clusterLock.Value); //Clear the locks if you reach 50 if (expiredLocks.Count() > 50) { await _clusterClient.Send(new ExecuteCommands() { Commands = expiredLocks.Select(el => new RemoveLock() { Name = el.Name, LockId = el.LockId }).ToList(), WaitForCommits = true }); expiredLocks = new List <Lock>(); } } } if (expiredLocks.Count() > 0) { await _clusterClient.Send(new ExecuteCommands() { Commands = expiredLocks.Select(el => new RemoveLock() { Name = el.Name, LockId = el.LockId }).ToList(), WaitForCommits = true }); } await Task.Delay(100); } catch (Exception e) { _logger.LogError("Failed to release locks with exception " + e.Message + Environment.NewLine + e.StackTrace); } } else { //Sleep for 10 seconds if you are not the leader. await Task.Delay(10000); } } }