I was wondering how you would use the TransactionScope class in the correct way when you are dealing with multithreading?
We create a new scope in our main thread and then we spawn off a couple of worker threads and we want these to participate in the main scope, so that for example the rollback is called on each worker if the scope is never completed.
I read something about TransactionScope using the ThreadStaticAttribute internally which made the above impossible / very difficult - could someone verify either way? If we run our code in a synchronized fashion then the rollbacks work, i.e the inner transactions are able to participate in the main transaction, but not if we switch over to a threaded execution.
The TransactionScope class provides a simple way to mark a block of code as participating in a transaction, without requiring you to interact with the transaction itself. A transaction scope can select and manage the ambient transaction automatically.
Multithreading is the ability of a program or an operating system to enable more than one user at a time without requiring multiple copies of the program running on the computer. Multithreading can also handle multiple requests from the same user.
Multi-threading with libcurllibcurl is thread safe but has no internal thread synchronization. You may have to provide your own locking should you meet any of the thread safety exceptions below. Handles. You must never share the same handle in multiple threads.
Multithreading is a form of parallelization or dividing up work for simultaneous processing. Instead of giving a large workload to a single core, threaded programs split the work into multiple software threads. These threads are processed in parallel by different CPU cores to save time.
See MSDN:
You should also use the TransactionScope and DependentTransaction class for applications that require the use of the same transaction across multiple function calls or multiple thread calls.
So maybe look into DependentTransaction
- in particular, there is a worker thread example, here.
This is correct: the TransactionScope
class uses the Transaction.Current
property that stores its value in the field, which is marked with the ThreadStatic
attribute.
The ThreadStatic
attribute makes sure that the field value gets thread affinity, i.e. it has unique value in each thread. It's the recommended approach to share data within a thread. It's also known as Thread Local Storage (TLS).
The TransactionScope
class just defines a transaction context in the current thread. It doesn't mean, however, that your code must accomplish all the job in that thread. I could imagine a complex calculation algorithm that uses multiple threads.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With