Performing the "atomic" operation "IncreaseIf" in the database

I need to execute the atom health check value for some field of some entity framework model and increase it if its value is 0.

I was thinking about transactions, for example:

bool controlPassed = false;
using (TransactionScope scope = new TransactionScope())
{
    var model = ...ModelEntities.first_or_default(...)
    if (model.field == 0){
        ++model.field;
        ...saveChanges();
        controlPassed = true;
    }
    scope.Complete();
}
if (controlPassed)
{
    ...
    using (TransactionScope scope = new TransactionScope())
    {
        --model.field;
        ...saveChanges();
        scope.Complete();
    }
}

Of course, everything is in try catch, etc.

My question is: how does it work?

This is really hard to verify. I have a multithreaded application.

Is it likely that two or more threads will transfer control (check that you field == 0increase it)?

What will be locked in the database (database, table, row, field)?

I cannot allow two or more threads to be in a section controlPassedat the same time.

+5
source share
1 answer

, ( == 0 )?

Serializable ( TransactionScope). , == 0, , , . , , ​​ . , RepeatableRead.

ReadCommitted ( SaveChanges TransactionScope MS SQL Server), , , EF - - , . () , .

ReadCommitted select, SQL- UPDLOCK ( ) . EF .

: concurrency, , , .

+10

All Articles