Note that Distributed Transactions are currently not supported on .Net Core, only on .Net Framework.
In order to use a TransactionScope
to span multiple threads, you'll need to use DependentClone to tie the threads into the parent TransactionScope
.
The steps are:
- Start a
TransactionScope
on your main / first thread
- Just before creating each thread, use
DependentClone
to create a DependentTransaction
, and then pass this DependentTransaction
instance to the new thread.
- On the child thread, you can use the
TransactionScope(DependentTransaction)
constructor overload to create a linked TransactionScope
, in which the child thread can perform local transactions.
- As the work on each child thread is completed successfully, then commit both the thread
TransactionScope
and the DependentTransaction
- On the main thread, wait until all threads are complete, and then commit the root
TransactionScope
There's some caveats too:
- Using
DependentTransaction
on multiple threads will immediately require the use of MSDTC.
- Using multiple threads under a large DTC transaction isn't going to make insertion into the same table any quicker (Use
SqlBulkCopy
for that), and you'll want to measure whether parallel inserts into different tables, same database under a DTC transaction warrants the locking overhead or returns any performance benefit.
- If you're using
async
, then you'll need TransactionScopeAsyncFlowOption.Enabled
More about Transction Scope here