TransactionScope not working with parallel extensions?

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 does not work. If I set a breakpoint on 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. Does anyone know why the parallel version is not working correctly?

+6
source share
2 answers

I have no idea what kind of technology this is, but transactions are usually thread-bound and do not extend to child threads. In doing so, you will need to start a new transaction in each thread. But this means that you will have as many independent transactions as threads.

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

+4
source

You can propagate the transaction to workflows 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 problems, this is not my native language

+4
source

Source: https://habr.com/ru/post/901838/


All Articles