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))
{
...
if (!_someRepository.IsValueExists(value))
_someRepository.AddData(value);
...
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))
{
...
transactionScope.IsolationLevel = IsolationLevel.ReadUncommitted;
lock (_sharedDataLockObject)
{
if (!_someRepository.IsValueExists(value))
_someRepository.AddData(value);
}
transactionScope.IsolationLevel = IsolationLevel.ReadCommitted;
...
transactionScope.Complete();
}
, TransactionScope IsolationLevel. , ADO.NET . , .