2011-11-18 54 views
6

如果我做到以下幾點:TransactionScope不能使用Parallel Extensions?

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 

一切都按預期工作。任何人都知道爲什麼並行版本無法正常工作?

回答

4

我不知道它是什麼技術,但通常事務是線程綁定的,不會傳播給子線程。這就是說你必須在每個線程中開始一個新的事務。但這意味着您將擁有與線程一樣多的獨立事務。

此限制是合理的,因爲事務附加到單線程的底層SQL數據庫連接。

4

您可以將交易傳播到工作線程如下:

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的語法問題,「那朵不是我的母語