Skip to content

Commit

Permalink
Refinement of the Polly policy for the deadlocked transactions retry …
Browse files Browse the repository at this point in the history
…logic.
  • Loading branch information
gmcelhanon committed Nov 7, 2024
1 parent 2f1389c commit 09c0a53
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -111,18 +111,33 @@ public async Task CreateAsync(TEntity entity, bool enforceOptimisticLock, Cancel
await DeadlockPolicyHelper.RetryPolicy.ExecuteAsync(
async ctx =>
{
using var trans = Session.BeginTransaction();
ITransaction trans = null;

try
{
trans = Session.BeginTransaction();
await Session.SaveAsync(entity, cancellationToken);
await trans.CommitAsync(cancellationToken);
}
catch (Exception)
{
await trans.RollbackAsync(cancellationToken);
// Check to see if we need to explicitly roll the transaction back
if (trans is { IsActive: true })
{
await trans.RollbackAsync(cancellationToken);
}

// Ensure the transaction is disposed to reset state before (potentially) retrying
trans?.Dispose();

// Re-throw to allow Polly to retry
throw;
}
finally
{
// Ensure transaction is disposed in all cases
trans?.Dispose();
}
},
_retryPolicyContextData);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,18 +43,33 @@ public async Task UpdateAsync(TEntity persistentEntity, CancellationToken cancel
await DeadlockPolicyHelper.RetryPolicy.ExecuteAsync(
async ctx =>
{
using var trans = Session.BeginTransaction();
ITransaction trans = null;

try
{
trans = Session.BeginTransaction();
await Session.UpdateAsync(persistentEntity, cancellationToken);
await trans.CommitAsync(cancellationToken);
}
catch (Exception)
{
await trans.RollbackAsync(cancellationToken);
// Check to see if we need to explicitly roll the transaction back
if (trans is { IsActive: true })
{
await trans.RollbackAsync(cancellationToken);
}

// Ensure the transaction is disposed to reset state before (potentially) retrying
trans?.Dispose();

// Re-throw to allow Polly to retry
throw;
}
finally
{
// Ensure transaction is disposed in all cases
trans?.Dispose();
}
},
_retryPolicyContextData);
}
Expand Down

0 comments on commit 09c0a53

Please sign in to comment.