使用事务范围实现隐式事务

TransactionScope 类提供一个简单方法,通过这一方法,您不必与事务本身交互,即可将代码块标记为参与某个事务。事务范围可以自动选择和管理环境事务。由于它易于使用并且效率很高,因此建议您在开发事务应用程序时使用 TransactionScope 类。

此外,您不必显式向事务登记资源。任何 System.Transactions 资源管理器(例如 SQL Server 2005)都可以检测到该范围创建的环境事务的存在并自动登记。

创建事务范围

下面的示例说明 TransactionScope 类的简单用法。

System.Transactions 基础结构既提供了基于 Transaction 类的显式编程模型,也提供了使用 TransactionScope 类的隐式编程模型,在后一种模型中,事务由该基础结构自动管理。

Note 重要事项:

建议使用 TransactionScope 类创建隐式事务,以便自动为您管理环境事务上下文。对于需要跨多个函数调用或多个线程调用使用相同事务的应用程序,您还应该使用 TransactionScope DependentTransaction 类。有关此模型的更多信息,请参见 使用事务范围实现隐式事务 主题。有关编写事务性应用程序的更多信息,请参见 编写事务性应用程序

 

在通过 new 语句实例化 TransactionScope 时,事务管理器将确定要参与哪个事务。一经确定,此范围将始终参与该事务。此决策基于两个因素:是否存在环境事务以及构造函数中 TransactionScopeOption 参数的值。环境事务是在其中执行您的代码的事务。通过调用 Transaction 类的 Current 静态属性可获取对环境事务的引用。有关如何使用此参数的更多信息,请参见 使用事务范围实现隐式事务 主题的“事务流管理”一节。

如果在事务范围中(即从初始化 TransactionScope 对象到调用其 Dispose 方法之间)未发生异常,则允许该范围所参与的事务继续。如果事务范围中的确发生了异常,它所参与的事务将回滚。

当应用程序完成它要在一个事务中执行的所有工作以后,您应当只调用 Complete 方法一次,以通知事务管理器可以接受提交事务。未能调用此方法将中止该事务。

Dispose 方法的调用标志着该事务范围的结束。在调用此方法之后发生的异常不会影响该事务。

如果在范围中修改 Current 的值,则会在调用 Dispose 时引发异常。但是,在该范围结束时,先前的值将被还原。此外,如果在创建事务的事务范围内对 Current 调用 Dispose ,则该事务将在相应范围末尾处中止。

下面的示例演示如何使用 TransactionScope 类定义代码块以参与事务。

 

// This function takes arguments for 2 connection strings and commands to create a transaction 

// involving two SQL Servers. It returns a value > 0 if the transaction is committed, 0 if the
// transaction is rolled back. To test this code, you can connect to two different databases
// on the same server by altering the connection string, or to another RDBMS such as Oracle
// by altering the code in the connection2 code block.
static public int CreateTransactionScope(
string connectString1, string connectString2,
string commandText1, string commandText2)
{
// Initialize the return value to zero and create a StringWriter to display results.
int returnValue = 0;
System.IO.StringWriter writer = new System.IO.StringWriter();

// Create the TransactionScope to execute the commands, guaranteeing
// that both commands can commit or roll back as a single unit of work.
using (TransactionScope scope = new TransactionScope())
{
using (SqlConnection connection1 = new SqlConnection(connectString1))
{
try
{
// Opening the connection automatically enlists it in the
// TransactionScope as a lightweight transaction.
connection1.Open();

// Create the SqlCommand object and execute the first command.
SqlCommand command1 = new SqlCommand(commandText1, connection1);
returnValue = command1.ExecuteNonQuery();
writer.WriteLine("Rows to be affected by command1: {0}" , returnValue);

// If you get here, this means that command1 succeeded. By nesting
// the using block for connection2 inside that of connection1, you
// conserve server and network resources as connection2 is opened
// only when there is a chance that the transaction can commit.
using (SqlConnection connection2 = new SqlConnection(connectString2))
try
{
// The transaction is escalated to a full distributed
// transaction when connection2 is opened.
connection2.Open();

// Execute the second command in the second database.
returnValue = 0;
SqlCommand command2 = new SqlCommand(commandText2, connection2);
returnValue = command2.ExecuteNonQuery();
writer.WriteLine("Rows to be affected by command2: {0}" , returnValue);
}
catch (Exception ex)
{
// Display information that command2 failed.
writer.WriteLine("returnValue for command2: {0}" , returnValue);
writer.WriteLine("Exception Message2: {0}" , ex.Message);
}
}
catch (Exception ex)
{
// Display information that command1 failed.
writer.WriteLine("returnValue for command1: {0}" , returnValue);
writer.WriteLine("Exception Message1: {0}" , ex.Message);
}
}

// The Complete method commits the transaction. If an exception has been thrown,
// Complete is not called and the transaction is rolled back.
scope.Complete();
}

// The returnValue is greater than 0 if the transaction committed.
if (returnValue > 0)
{
writer.WriteLine("Transaction was committed." );
}
else
{
// You could write additional business logic here, for example, you can notify the caller
// by throwing a TransactionAbortedException, or logging the failure.
writer.WriteLine("Transaction rolled back." );
}

// Display messages.
Console.WriteLine(writer.ToString());

return returnValue;
}
System.Object
   System.Transactions.TransactionScope

该类型对于多线程操作是安全的。

 

 

即只要将

using
 (TransactionScope scope = new
 TransactionScope()) 数据库处理的代码包含在此模块内即可成为事务。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值