TransactionScope 和多线程

发布于 2024-07-15 01:55:45 字数 279 浏览 10 评论 0原文

我想知道在处理多线程时如何正确使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

柏林苍穹下 2024-07-22 01:55:45

请参阅 MSDN

您还应该使用 TransactionScope 和
DependentTransaction 类
需要使用的应用程序
同一交易跨多个
函数调用或多线程
来电。

因此,也许可以查看 DependentTransaction - 特别是,有一个工作线程示例,此处

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.

凉城已无爱 2024-07-22 01:55:45

这是正确的:TransactionScope 类使用 Transaction.Current 属性将其值存储在字段中,该字段用 ThreadStatic 属性标记。

ThreadStatic 属性确保字段值具有线程关联性,即它在每个线程中具有唯一的值。 这是在线程内共享数据的推荐方法。 它也称为线程本地存储 (TLS)。

TransactionScope 类仅定义当前线程中的事务上下文。 然而,这并不意味着您的代码必须完成该线程中的所有工作。 我可以想象一个使用多个线程的复杂计算算法。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文