语言

TransactionScope 类

定义

使代码块成为事务性代码块。 此类不能被继承。

public ref class TransactionScope sealed : IDisposable
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
public sealed class TransactionScope : IDisposable
public sealed class TransactionScope : IDisposable
[<System.Runtime.Versioning.UnsupportedOSPlatform("browser")>]
type TransactionScope = class
    interface IDisposable
type TransactionScope = class
    interface IDisposable
Public NotInheritable Class TransactionScope
Implements IDisposable
继承
TransactionScope
属性
实现

示例

下面的示例演示如何使用 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 3rd party RDBMS 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();

    try
    {
        // 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))
            {
                // 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))
                {
                    // 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);
                }
            }

            // The Complete method commits the transaction. If an exception has been thrown,
            // Complete is not  called and the transaction is rolled back.
            scope.Complete();
        }
    }
    catch (TransactionAbortedException ex)
    {
        writer.WriteLine("TransactionAbortedException Message: {0}", ex.Message);
    }

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

    return returnValue;
}
'  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 3rd party RDBMS  
'  by altering the code in the connection2 code block.
Public Function CreateTransactionScope( _
  ByVal connectString1 As String, ByVal connectString2 As String, _
  ByVal commandText1 As String, ByVal commandText2 As String) As Integer

    ' Initialize the return value to zero and create a StringWriter to display results.
    Dim returnValue As Integer = 0
    Dim writer As System.IO.StringWriter = New System.IO.StringWriter

    Try
    ' Create the TransactionScope to execute the commands, guaranteeing
    '  that both commands can commit or roll back as a single unit of work.
        Using scope As New TransactionScope()
            Using connection1 As New SqlConnection(connectString1)
                ' Opening the connection automatically enlists it in the 
                ' TransactionScope as a lightweight transaction.
                connection1.Open()

                ' Create the SqlCommand object and execute the first command.
                Dim command1 As SqlCommand = 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 connection2 As New SqlConnection(connectString2)
                    ' 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
                    Dim command2 As SqlCommand = New SqlCommand(commandText2, connection2)
                    returnValue = command2.ExecuteNonQuery()
                    writer.WriteLine("Rows to be affected by command2: {0}", returnValue)
                End Using
            End Using

        ' The Complete method commits the transaction. If an exception has been thrown,
        ' Complete is called and the transaction is rolled back.
        scope.Complete()
        End Using
    Catch ex As TransactionAbortedException
        writer.WriteLine("TransactionAbortedException Message: {0}", ex.Message)
    End Try

    ' Display messages.
    Console.WriteLine(writer.ToString())

    Return returnValue
End Function

注解

基础结构 System.Transactions 提供基于 Transaction 类的显式编程模型,以及使用该类的 TransactionScope 隐式编程模型,其中事务由基础结构自动管理。

Important

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

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

如果在事务范围(即对象初始化 TransactionScope 与其 Dispose 方法的调用之间)中没有发生异常,则允许范围参与的事务继续。 如果在事务范围内发生异常,将回滚其参与的事务。

当应用程序完成要在事务中执行的所有工作时,应仅调用 Complete 一次方法,告知事务管理器提交事务是可以接受的。 未能调用此方法中止事务。

对 Dispose 方法的调用标记事务范围的末尾。 调用此方法后发生的异常可能不会影响事务。

如果修改作用域内的值 Current ,则会在调用时 Dispose 引发异常。 但是,在作用域末尾,将还原上一个值。 此外,如果在创建事务的事务范围内调用DisposeCurrent,则事务会在作用域末尾中止。

构造函数

名称 说明
TransactionScope()

初始化 TransactionScope 类的新实例。

TransactionScope(Transaction, TimeSpan, EnterpriseServicesInteropOption)

使用指定的超时值和 COM+ 互操作性要求初始化类的新实例 TransactionScope ,并将指定的事务设置为环境事务,以便作用域内完成的事务工作使用此事务。

TransactionScope(Transaction, TimeSpan, TransactionScopeAsyncFlowOption)

[.NET Framework 4.5.1 及更高版本中受支持]

使用指定的超时值初始化类的新实例 TransactionScope ,并将指定的事务设置为环境事务,以便作用域内完成的事务工作使用此事务。

TransactionScope(Transaction, TimeSpan)

使用指定的超时值初始化类的新实例 TransactionScope ,并将指定的事务设置为环境事务,以便作用域内完成的事务工作使用此事务。

TransactionScope(Transaction, TransactionScopeAsyncFlowOption)

[.NET Framework 4.5.1 及更高版本中受支持]

初始化类的新实例 TransactionScope ,并将指定的事务设置为环境事务,以便作用域内完成的事务工作使用此事务。

TransactionScope(Transaction)

初始化类的新实例 TransactionScope ,并将指定的事务设置为环境事务,以便作用域内完成的事务工作使用此事务。

TransactionScope(TransactionScopeAsyncFlowOption)

使用指定的异步流选项初始化类的新实例 TransactionScope 。

TransactionScope(TransactionScopeOption, TimeSpan, TransactionScopeAsyncFlowOption)

使用指定的超时值、要求和异步流选项初始化类的新实例 TransactionScope 。

TransactionScope(TransactionScopeOption, TimeSpan)

使用指定的超时值和要求初始化类的新实例 TransactionScope 。

TransactionScope(TransactionScopeOption, TransactionOptions, EnterpriseServicesInteropOption)

使用指定的作用域和 COM+ 互操作性要求和事务选项初始化类的新实例 TransactionScope 。

TransactionScope(TransactionScopeOption, TransactionOptions, TransactionScopeAsyncFlowOption)

[.NET Framework 4.5.1 及更高版本中受支持]

使用指定的要求和异步流选项初始化类的新实例 TransactionScope 。

TransactionScope(TransactionScopeOption, TransactionOptions)

使用指定的要求初始化类的新实例 TransactionScope 。

TransactionScope(TransactionScopeOption, TransactionScopeAsyncFlowOption)

使用指定的要求和异步流选项初始化类的新实例 TransactionScope 。

TransactionScope(TransactionScopeOption)

使用指定的要求初始化类的新实例 TransactionScope 。

方法

名称 说明
Complete()

指示作用域中的所有操作都已成功完成。

Dispose()

结束事务范围。

Equals(Object)

确定指定的对象是否等于当前对象。

(继承自 Object)
GetHashCode()

用作默认哈希函数。

(继承自 Object)
GetType()

获取当前实例的 Type。

(继承自 Object)
MemberwiseClone()

创建当前 Object的浅表副本。

(继承自 Object)
ToString()

返回一个表示当前对象的字符串。

(继承自 Object)

适用于

线程安全性

此类型是线程安全的。

另请参阅