TransactionScope 和多线程
我想知道在处理多线程时如何正确使用 TransactionScope 类?
我们在主线程中创建一个新的作用域,然后生成几个工作线程,我们希望这些线程参与主作用域,因此,如果作用域从未完成,则在每个工作线程上调用回滚。
我读到了一些关于 TransactionScope 在内部使用 ThreadStaticAttribute 的内容,这使得上述不可能/非常困难 - 有人可以验证这两种方式吗? 如果我们以同步方式运行代码,那么回滚就会起作用,即内部事务能够参与主事务,但如果我们切换到线程执行则不会。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请参阅 MSDN:
因此,也许可以查看 DependentTransaction - 特别是,有一个工作线程示例,此处。
See MSDN:
So maybe look into
DependentTransaction
- in particular, there is a worker thread example, here.这是正确的:
TransactionScope
类使用Transaction.Current
属性将其值存储在字段中,该字段用ThreadStatic
属性标记。ThreadStatic
属性确保字段值具有线程关联性,即它在每个线程中具有唯一的值。 这是在线程内共享数据的推荐方法。 它也称为线程本地存储 (TLS)。TransactionScope
类仅定义当前线程中的事务上下文。 然而,这并不意味着您的代码必须完成该线程中的所有工作。 我可以想象一个使用多个线程的复杂计算算法。This is correct: the
TransactionScope
class uses theTransaction.Current
property that stores its value in the field, which is marked with theThreadStatic
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.