简体   繁体   English

TransactionScope 和多线程

[英]TransactionScope and multi-threading

I was wondering how you would use the TransactionScope class in the correct way when you are dealing with multithreading?我想知道在处理多线程时如何以正确的方式使用 TransactionScope class?

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.我们在主线程中创建了一个新的 scope,然后我们产生了几个工作线程,我们希望这些工作线程参与到主 scope 中,例如,如果 Z31A1FD140BE4BEF2D11E121EC9A 从未完成,则在每个工作线程上调用回滚。

I read something about TransactionScope using the ThreadStaticAttribute internally which made the above impossible / very difficult - could someone verify either way?我在内部使用 ThreadStaticAttribute 阅读了有关 TransactionScope 的一些内容,这使得上述不可能/非常困难 - 有人可以验证任何一种方式吗? If we run our code in a synchronized fashion then the rollbacks work, ie the inner transactions are able to participate in the main transaction, but not if we switch over to a threaded execution.如果我们以同步方式运行我们的代码,那么回滚工作,即内部事务能够参与主事务,但如果我们切换到线程执行则不能。

See MSDN :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.对于需要跨多个 function 调用或多线程调用使用相同事务的应用程序,您还应该使用 TransactionScope 和 DependentTransaction class。

So maybe look into DependentTransaction - in particular, there is a worker thread example, here .所以也许看看DependentTransaction - 特别是, 这里有一个工作线程示例。

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.这是正确的: TransactionScope class 使用Transaction.Current属性将其值存储在字段中,该字段用ThreadStatic属性标记。

The ThreadStatic attribute makes sure that the field value gets thread affinity, ie it has unique value in each thread. ThreadStatic属性确保字段值获得线程亲和性,即它在每个线程中具有唯一值。 It's the recommended approach to share data within a thread.这是在线程共享数据的推荐方法。 It's also known as Thread Local Storage (TLS).它也称为线程本地存储(TLS)。

The TransactionScope class just defines a transaction context in the current thread. TransactionScope class 只是在当前线程中定义了一个事务上下文。 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.我可以想象一个使用多个线程的复杂计算算法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM