且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

实体框架6和悲观并发

更新时间:2023-02-13 16:52:44

实现悲观并发的一种方法是使用类似以下的方法:

One way to acheive pessimistic concurrency is to use sonething like this:

var options = new TransactionOptions
{
   IsolationLevel = System.Transactions.IsolationLevel.Serializable,
   Timeout = new TimeSpan(0, 0, 0, 10)
};

using(var scope = new TransactionScope(TransactionScopeOption.RequiresNew, options))
{ ... stuff here ...}

在VS2017中,您似乎必须右键单击TransactionScope,然后获取它以添加以下引用:Reference Assemblies \ Microsoft \ Framework.NETFramework \ v4.6.1 \ System.Transactions.dll

In VS2017 it seems you have to rightclick TransactionScope then get it to add a reference for: Reference Assemblies\Microsoft\Framework.NETFramework\v4.6.1\System.Transactions.dll

但是,如果有两个线程尝试递增同一计数器,则会发现一个成功,而另一个线程在10秒内发出超时.这样做的原因是,当他们继续保存更改时,他们都需要将其锁升级为独占,但不能这样做,因为其他事务已经在同一行上持有共享锁.然后,SQL Server将在一段时间内使一个事务解决该死锁失败后检测到该死锁.失败的一个事务将释放共享锁,第二个事务将能够将其共享锁升级为排他锁并继续执行.

However if you have two threads attempt to increment the same counter, you will find one succeeds whereas the other thread thows a timeout in 10 seconds. The reason for this is when they proceed to saving changes they both need to upgrade their lock to exclusive, but they cannot because other transaction is already holding a shared lock on the same row. SQL Server will then detect the deadlock after a while fails one transactions to solve the deadlock. Failing one transaction will release shared lock and the second transaction will be able to upgrade its shared lock to exclusive lock and proceed with execution.

摆脱这种僵局的方法是使用诸如

The way out of this deadlocking is to provide a UPDLOCK hint to the database using something such as:

private static TestEntity GetFirstEntity(Context context) {
return context.TestEntities
              .SqlQuery("SELECT TOP 1 Id, Value FROM TestEntities WITH (UPDLOCK)")
              .Single();
}

此代码来自Ladislav Mrnka的博客,该博客现在似乎不可用.另一种选择是求助于乐观锁定.

This code came from Ladislav Mrnka's blog which now looks to be unavailable. The other alternative is to resort to optimistic locking.