事务范围(TransactionScope)是如何工作的?

32
Method1()实例化一个TransactionScope并调用Method2(),后者也实例化一个TransactionScope时,.NET如何知道两者在同一作用域内? 我认为它不会在内部使用静态方法,否则在像ASP.NET这样的多线程应用程序中可能无法正常工作。
是否可以创建类似于TransactionScope的自定义类,还是原始类使用特殊功能只有微软知道如何运作?

3
有点跑题,所以我来做一个注释:静态方法对于多线程并不是大问题,你需要担心的是静态数据。 - µBio
3个回答

20
希望这可以帮助:

http://msdn.microsoft.com/en-us/magazine/cc300805.aspx

For those unfamiliar with TransactionScope, it is part of the System.Transactions namespace new to the Microsoft® .NET Framework 2.0. System.Transactions provides a transactions framework fully integrated into the .NET Framework, including but not limited to ADO.NET. The Transaction and TransactionScope classes are two of the most important classes in this namespace. As the question alludes to, you can create a TransactionScope instance, and ADO.NET operations executed within the scope of that TransactionScope will be enlisted automatically (you can also access the current Transaction through the Transaction.Current static property):

using(TransactionScope scope = new TransactionScope())
{
    ... // all operations here part of a transaction
    scope.Complete();
}


9

TransactionScope 基本上是建立在 COM 之上的 - 具体来说是在 MSDTC 上。

这个协调事务,并允许嵌套事务。

简而言之,当您首次调用 TransactionScope 时,一个事务将在 MSDTC 中注册,所有对 TransactionScope 的调用都会如此。 MSDTC 协调它们所有。


2
有时候事务(特别是数据库事务)会被提升到DTC,但并非总是如此。 - Eduardo
@Eduardo - 这是真的。LTM(轻量级事务管理器)可以通过MSDTC将事务升级为分布式。 - Oded

0
答案是,执行可以由TransactionScope保护、提交和回滚的操作的类必须专门编写以了解“环境”事务。(这不是魔法。)这个答案很好地解释了它:如何在TransactionScope中注册?

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接