使用的TransactionScope RequiresNew的下行TransactionScope、RequiresNew

2023-09-03 06:08:30 作者:窦:情窦未开、窦你玩

我想明白了什么是/ TransactionScopeOption.RequiresNew 使用下行在的EntityFramework ( W / SQL Server中的贸易2008 ),什么是我们为什么不应该使用的原因 RequiresNew 总是

I want to understand what is the trade-of/downside of using TransactionScopeOption.RequiresNew on EntityFramework (w/ Sql Server 2008), what are the reasons why we should NOT use RequiresNew always.

问候。

推荐答案

您应该使用必需不是 RequiresNew 。 RequiresNew意味着每一个操作将采用一个新的事务,即使有一个包含现有的交易范围。这肯定会导致死锁。即使必需还有另一个严重的问题的TransactionScope ,即它默认创建一个序列化交易,这是一个可怕的错误的选择,但另一个快捷死锁地狱,没有可扩展性。请参阅using新的TransactionScope()是有害的。你应该总是创建具有明确的的TransactionOption 设置隔离级别的事务范围, READCOMMITTED ,其中一个非常非常多理智的隔离级别:

You should use Required not RequiresNew. RequiresNew means every operation will use a new transaction, even if there is an encompassing already existing transaction scope. This will certainly lead to deadlocks. Even with Required there is another serious problem with TransactionScope, namely that it creates by default a Serializable transaction, which is a horribly bad choice and yet another shortcut to deadlock hell and no scalability. See using new TransactionScope() Considered Harmful. You should always create a transaction scope with the explicit TransactionOption setting the isolation level to ReadCommitted, which a much much much more sane isolation level:

using(TransactionScope scope = new TransactionScope(
    TransactionScopeOption.Required,
    new TransactionOptions {
       IsolationLevel = IsolationLevel.ReadCommitted}))
{
   /// do work here
   ...
   scope.Complete();
}