Skip to main content
 首页 » 编程设计

.net之TransactionScope 和多线程

2024年08月16日3998°冷暖

我想知道在处理多线程时如何正确使用 TransactionScope 类?

我们在主线程中创建一个新的作用域,然后生成几个工作线程,我们希望它们参与主作用域,因此,如果作用域从未完成,则在每个工作线程上调用回滚.

我读到了一些关于 TransactionScope 在内部使用 ThreadStaticAttribute 的内容,这使得上述不可能/非常困难 - 有人可以验证这两种方式吗?如果我们以同步方式运行代码,那么回滚就会起作用,即内部事务能够参与主事务,但如果我们切换到线程执行则不会。

请您参考如下方法:

参见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.

所以也许可以看看DependentTransaction - 特别是,有一个工作线程示例,here .