C# System.Transactions 与 TransactionScope

C# System.Transactions Vs TransactionScope

根据这篇文章 here as well as the question: Difference Between Transaction and TransactionScope 我们知道 TransactionScope

The TransactionScope class provides a simple way to mark a block of code as participating in a transaction, without requiring you to interact with the transaction itself. A transaction scope can select and manage the ambient transaction automatically. Due to its ease of use and efficiency, it is recommended that you use the TransactionScope class when developing a transaction application.

System.Transactions.Transaction

The Transaction class contains methods used by developers implementing resource managers for enlistment. It also provides functionalities for cloning a transaction and controlling the current transaction context.

这里的问题是是否有办法选择使用两者中的哪一个。如果您没有理由使用显式交易,那么显而易见的答案是使用隐式交易,但那是什么原因呢?

是否存在显式事务,仅支持遗留实现?

环顾各种资源,我偶然发现了以下部分回答了我的问题:Working with transactions in EF 6

基于此文档(主要基于 EF,但似乎仍然存在限制):

There are still some limitations to the TransactionScope approach:

Requires .NET 4.5.1 or greater to work with asynchronous methods.

  • It cannot be used in cloud scenarios unless you are sure you have one and only one connection (cloud scenarios do not support distributed transactions).
  • It cannot be combined with the Database.UseTransaction() approach of the previous sections.
  • It will throw exceptions if you issue any DDL and have not enabled distributed transactions through the MSDTC Service.

Advantages of the TransactionScope approach:

  • It will automatically upgrade a local transaction to a distributed transaction if you make more than one connection to a given database or combine a connection to one database with a connection to a different database within the same transaction (note: you must have the MSDTC service configured to allow distributed transactions for this to work).
  • Ease of coding. If you prefer the transaction to be ambient and dealt with implicitly in the background rather than explicitly under you control then the TransactionScope approach may suit you better.

由于不再支持第一篇文章并且 EF 6 文章较新 + 来自@MarcGravell 的评论,我认为决定归结为上述 EF 6 文章的优点和缺点。