25
25
using System . Threading ;
26
26
using System . Transactions ;
27
27
using Dapper ;
28
+ using Hangfire . Annotations ;
28
29
using Hangfire . Logging ;
29
30
using Npgsql ;
30
31
using IsolationLevel = System . Data . IsolationLevel ;
@@ -126,7 +127,7 @@ public static void Lock(string resource, TimeSpan timeout, IDbConnection connect
126
127
IDbTransaction trx = null ;
127
128
try
128
129
{
129
- TryBeginTransaction ( connection , out trx ) ;
130
+ trx = BeginTransactionIfNotPresent ( connection ) ;
130
131
131
132
int rowsAffected = connection . Execute ( $@ "
132
133
INSERT INTO ""{ options . SchemaName } "".""lock""(""resource"", ""acquired"")
@@ -189,7 +190,7 @@ private static void TryRemoveLock(string resource, IDbConnection connection, Pos
189
190
IDbTransaction trx = null ;
190
191
try
191
192
{
192
- TryBeginTransaction ( connection , out trx ) ;
193
+ trx = BeginTransactionIfNotPresent ( connection ) ;
193
194
connection . Execute ( $@ "DELETE FROM ""{ options . SchemaName } "".""lock"" WHERE ""resource"" = @Resource AND ""acquired"" < @Timeout",
194
195
new {
195
196
Resource = resource ,
@@ -208,11 +209,12 @@ private static void TryRemoveLock(string resource, IDbConnection connection, Pos
208
209
}
209
210
}
210
211
211
- private static void TryBeginTransaction ( IDbConnection connection , out IDbTransaction trx )
212
+ [ CanBeNull ]
213
+ private static IDbTransaction BeginTransactionIfNotPresent ( IDbConnection connection )
212
214
{
213
215
// If transaction scope was created outside of hangfire, the newly-opened connection is automatically enlisted into the transaction.
214
216
// Starting a new transaction throws "A transaction is already in progress; nested/concurrent transactions aren't supported." in that case.
215
- trx = Transaction . Current == null ? connection . BeginTransaction ( IsolationLevel . ReadCommitted ) : null ;
217
+ return Transaction . Current == null ? connection . BeginTransaction ( IsolationLevel . ReadCommitted ) : null ;
216
218
}
217
219
}
218
220
0 commit comments