【问题标题】:TransactionScope not working with Parallel Extensions?TransactionScope 不能与并行扩展一起使用?
【发布时间】:2011-11-18 19:29:03
【问题描述】:

如果我执行以下操作:

 Using scope = New TransactionScope()
        entries.Content.ReadAs(Of IList(Of WebMaint)).AsParallel.ForAll(Sub(entry)
                                                                            _repos.Update(entry)
                                                                        End Sub)
        scope.Complete()
    End Using

TransactionScope 不起作用。如果我在 scope.complete 上设置断点,则没有事务处于活动状态并且更新已经完成。

如果我将其更改为:

Using scope = New TransactionScope()
            entries.Content.ReadAs(Of IList(Of WebMaint)).ToList().ForEach(Sub(entry)
                                                                               _repos.Update(entry)
                                                                           End Sub)
            scope.Complete()
End Using

一切都按预期进行。有人知道为什么并行版本不能正常工作吗?

【问题讨论】:

    标签: .net transactionscope parallel-extensions


    【解决方案1】:

    我不知道它是什么技术,但通常事务是线程绑定的,不会传播到子线程。话虽如此,您将不得不在每个线程中启动一个新事务。但这意味着您将拥有与线程一样多的独立事务。

    此限制是合理的,因为事务附加到单线程的底层 SQL 数据库连接。

    【讨论】:

      【解决方案2】:

      您可以将事务传播到工作线程,如下所示:

      Using scope = New TransactionScope()
          Dim rootTransaction As Transaction  = Transaction.Current
      
          entries.Content.ReadAs(Of IList(Of WebMaint)).AsParallel.ForAll(
              Sub(entry)    
                  Dim dependentTransaction As DependentTransaction = rootTransaction.DependentClone(DependentCloneOption.RollbackIfNotComplete)
      
                  _repos.Update(entry)
      
                  dependentTransaction.Complete()
              End Sub)        
      
          scope.Complete()
      End Using
      

      注意:请原谅任何 VB 语法问题,这不是我的母语

      【讨论】:

        猜你喜欢
        • 2021-06-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-14
        • 2013-09-10
        • 1970-01-01
        相关资源
        最近更新 更多