TransactionScope not working with Parallel Extensions?

夙愿已清 提交于 2020-01-11 05:14:46

问题


If i do the following:

 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 doesn't work. If i put a breakpoint on the scope.complete no transaction is active and the updates are already complete.

If i change it to:

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

Everything works as expected. Anyone know why the parallel version doesn't work correctly?


回答1:


I have no idea what technology is it, but typically transactions are thread bound and do not propagate to children threads. That being said you will have to start a new transaction in each thread. But this means you will have as many independent transactions as threads.

This limitation is reasonable since the transaction is attached to the underlying SQL database connection which is single threaded.




回答2:


You can propagate the transaction to the worker threads as follows:

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

NOTE: please forgive any VB syntax issues, 'tis not my native tongue



来源:https://stackoverflow.com/questions/8188009/transactionscope-not-working-with-parallel-extensions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!