public Result<bool> Execute(IAggregateRootId aggregateRootId, int aggregateRootRevision, Action action) { var result = new Result<bool>(false); var acquired = new AtomicBoolean(false); try { if (aggregateLock.TryGetValue(aggregateRootId, out acquired) == false) { acquired = acquired ?? new AtomicBoolean(false); if (aggregateLock.TryAdd(aggregateRootId, acquired) == false) aggregateLock.TryGetValue(aggregateRootId, out acquired); } if (acquired.CompareAndSet(false, true)) { try { AtomicInteger revision = null; if (aggregateRevisions.TryGetValue(aggregateRootId, out revision) == false) { revision = new AtomicInteger(aggregateRootRevision - 1); if (aggregateRevisions.TryAdd(aggregateRootId, revision) == false) return result; } var currentRevision = revision.Value; if (revision.CompareAndSet(aggregateRootRevision - 1, aggregateRootRevision)) { try { action(); return Result.Success; } catch (Exception) { revision.GetAndSet(currentRevision); throw; } } } finally { acquired.GetAndSet(false); } } return result; } catch (Exception ex) { return result.WithError(ex); } }