C# System.Transactions 与 TransactionScope [英] C# System.Transactions Vs TransactionScope

查看:39
本文介绍了C# System.Transactions 与 TransactionScope的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于本文这里以及问题:交易和交易范围的区别我们知道TransactionScope

Based on this article here as well as the question: Difference Between Transaction and TransactionScope we know that TransactionScope

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.

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

The question here is whether there is a way to chose which of the two to use. The obvious answer is to use implicit transactions if you have no reason to use explicit, but what would that reason be?

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

Are the explicit transactions there, only to support legacy implementations?

推荐答案

环顾各种资源,我偶然发现以下部分回答了我的问题:在 EF 6 中处理事务

Looking around various resources, I stumbled to the following which partially answers my question: Working with transactions in EF 6

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

Based on this documentation (which is mostly based on EF but limitations seem to apply anyway):

TransactionScope 方法仍有一些限制:

需要 .NET 4.5.1 或更高版本才能使用异步方法.

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

  • 除非您确定只有一个连接(云场景不支持分布式事务),否则不能在云场景中使用.
  • 它不能与前几节的 Database.UseTransaction() 方法结合使用.
  • 如果您发出任何 DDL 并且没有通过 MSDTC 服务启用分布式事务,它将抛出异常.

TransactionScope 方法的优势:

  • 如果您与一个给定的数据库建立多个连接,或者将一个数据库的连接与同一事务中不同数据库的连接组合在一起,它会自动将本地事务升级为分布式事务(注意:您必须具有MSDTC 服务配置为允许分布式事务以使其工作).
  • 易于编码.如果您希望事务是环境事务并在后台隐式处理而不是明确在您的控制之下,那么 TransactionScope 方法可能更适合您.

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

Being that the first article is no longer supported and the EF 6 article is newer + the comment from @MarcGravell, I assume that the decision comes down to the advantages and disadvantages of the EF 6 article above.

这篇关于C# System.Transactions 与 TransactionScope的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆