使用TransactionScope需要新功能的缺点

Bon*_*arp 13 .net c# sql entity-framework

我想了解TransactionScopeOption.RequiresNewEntityFramework(w/Sql Server 2008)上使用的交易/缺点是什么,我们不应该RequiresNew总是使用的原因是什么.

问候.

Rem*_*anu 23

您应该使用Required没有RequiresNew.RequiresNew意味着每个操作都将使用新事务,即使存在包含已存在的事务范围.这肯定会导致僵局.即使Required存在另一个严重的问题TransactionScope,即它默认创建一个Serializable事务,这是一个非常糟糕的选择,也是死锁地狱的另一个捷径,没有可扩展性.请参阅使用新的TransactionScope()认为有害.您应该始终使用显式TransactionOption设置隔离级别来创建事务范围ReadCommitted,这是一个更加理智的隔离级别:

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

  • 有时,`RequiresNew`对于记录或审计非常有用,无论包含哪些事务,都应该成功.我同意,在使用之前要仔细考虑. (2认同)
  • @BrianLow:但是除非您的日志/审计代码使用`IEnlistmentNotification`,否则它总是会记录并且如果外部事务失败则永远不会回滚? (2认同)