Transaction Scope Nuances

Suppose I have two threads that execute some database-oriented code in TransactionScopes stream transactions with ReadCommitted isolation level. But there is a table whose data should be divided (duplicates should not be created).

using (var transactionScope = new TransactionScope(IsolationLevel.ReadCommitted))
{
   ...//some code
   if (!_someRepository.IsValueExists(value))
      _someRepository.AddData(value);
   ...//some code
   transactionScope.Complete();
}

The problem is that both streams can check if the data exists at about the same time, and if not, create duplicate data (restrictions will not help here: I have to prevent an exception). I think this is a trivial problem, but how is it usually solved?

I see the following schematic solution:

using (var transactionScope = new TransactionScope(IsolationLevel.ReadCommitted))
{
   ...//some code
   transactionScope.IsolationLevel = IsolationLevel.ReadUncommitted; //change Isolation Level
   lock (_sharedDataLockObject)
   {
      if (!_someRepository.IsValueExists(value))
         _someRepository.AddData(value);
   }
   transactionScope.IsolationLevel = IsolationLevel.ReadCommitted; //reset IsolationLevel
   ...//some code
   transactionScope.Complete();
}

, TransactionScope IsolationLevel. , ADO.NET . , .

+3
2

DB try-catch catch. , - , (, ). , " " ).

, , , , .

, . .

+1

.

, , .

.

,

,

.

+2

Source: https://habr.com/ru/post/1792075/


All Articles