Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how TransactionScope work with multi-threads

Hi firstly thank you for your attention on this question; Is there any way to implement a transaction like this in c#

using (Transactionscope x=new Transactionscope ())
{

   Thead A()=> Independent Transactionscope()  A(Insert into table X )

   Thead B()=> Independent Transactionscope()  B(Insert into table Y )

   Thead C()=> Independent Transactionscope()  C(Insert into table Z )

   Thread.WaitAll(A,B,C)

  commit big transaction x/ rollback big transaction x
}
like image 217
frank_liu Avatar asked Feb 20 '26 10:02

frank_liu


1 Answers

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:

  1. Start a TransactionScope on your main / first thread
  2. Just before creating each thread, use DependentClone to create a DependentTransaction, and then pass this DependentTransaction instance to the new thread.
  3. 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.
  4. As the work on each child thread is completed successfully, then commit both the thread TransactionScope and the DependentTransaction
  5. On the main thread, wait until all threads are complete, and then commit the root TransactionScope

There's some caveats too:

  1. Using DependentTransaction on multiple threads will immediately require the use of MSDTC.
  2. 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.
  3. If you're using async, then you'll need TransactionScopeAsyncFlowOption.Enabled

More about Transction Scope here

like image 52
StuartLC Avatar answered Feb 23 '26 01:02

StuartLC