TransactionScope 類別

定義

使程式碼區塊成為異動式。 此類別無法獲得繼承。

public ref class TransactionScope sealed : IDisposable
public sealed class TransactionScope : IDisposable
[System.Runtime.Versioning.UnsupportedOSPlatform("browser")]
public sealed class TransactionScope : IDisposable
type TransactionScope = class
    interface IDisposable
[<System.Runtime.Versioning.UnsupportedOSPlatform("browser")>]
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 類別的隱含程式設計模型,其中交易會自動由基礎結構管理。

重要

建議您使用 TransactionScope 類別建立隱含交易,以便為您自動管理環境交易內容。 您也應該針對需要跨多個函式呼叫或多個執行緒呼叫使用相同的交易的應用程式,使用 TransactionScopeDependentTransaction 類別。 如需此模型的詳細資訊,請參閱 使用交易範圍實作隱含交易 主題。 如需撰寫交易式應用程式的詳細資訊,請參閱 撰寫交易式應用程式

由 語句具現化 TransactionScopenew 時,交易管理員會決定要參與的交易。 一旦決定後,範圍永遠會參與該異動。 此決策是根據兩個因素而定:環境異動是否存在,以及建構函式中的 TransactionScopeOption 參數值。 環境交易是您程式碼執行所在的交易。 您可以呼叫 Transaction.Current 類別的靜態 Transaction 屬性,取得環境交易的參考。 如需如何使用此參數的詳細資訊,請參閱 使用交易範圍實作隱含交易 主題的一節。

如果在交易範圍內發生任何例外狀況, (也就是說,物件初始化 TransactionScope 與其 Dispose 方法呼叫) 之間,則允許範圍參與的交易繼續進行。 如果在交易範圍內發生例外狀況,則會回復參與的交易。

當您的應用程式完成所有想要在交易中執行的工作時,您應該只呼叫 Complete 方法一次,通知交易管理員認可交易是可接受的。 無法呼叫這個方法會中止交易。

對 方法的 Dispose 呼叫會標示交易範圍的結尾。 在呼叫這個方法後發生的例外狀況不太可能會影響異動。

如果您在範圍內修改 的值 Current ,則會在呼叫 時 Dispose 擲回例外狀況。 不過,在範圍的結尾,會還原先前的值。 此外,如果您在建立交易的交易範圍內呼叫 DisposeCurrent ,則交易會在範圍結尾中止。

建構函式

TransactionScope()

初始化 TransactionScope 類別的新執行個體。

TransactionScope(Transaction)

初始化 TransactionScope 類別的新執行個體,並將指定的異動設定為環境異動,以便在範圍內執行的異動式工作使用這個異動。

TransactionScope(Transaction, TimeSpan)

使用指定的逾時值,初始化 TransactionScope 類別的新執行個體,並將指定的異動設定為環境異動,以便在範圍內執行的異動式工作使用這個異動。

TransactionScope(Transaction, TimeSpan, EnterpriseServicesInteropOption)

使用指定的逾時值和 COM+ 互通性需求,初始化 TransactionScope 類別的新執行個體,並將指定的異動設定為環境異動,以便在範圍內執行的異動式工作使用這個異動。

TransactionScope(Transaction, TimeSpan, TransactionScopeAsyncFlowOption)

[在 .NET Framework 4.5.1 及更新版本中支援]

使用指定的逾時值,初始化 TransactionScope 類別的新執行個體,並將指定的異動設定為環境異動,以便在範圍內執行的異動式工作使用這個異動。

TransactionScope(Transaction, TransactionScopeAsyncFlowOption)

[在 .NET Framework 4.5.1 及更新版本中支援]

初始化 TransactionScope 類別的新執行個體,並將指定的異動設定為環境異動,以便在範圍內執行的異動式工作使用這個異動。

TransactionScope(TransactionScopeAsyncFlowOption)

使用指定的非同步流程選項,初始化 TransactionScope 類別的新執行個體。

TransactionScope(TransactionScopeOption)

使用指定的需求,初始化 TransactionScope 類別的新執行個體。

TransactionScope(TransactionScopeOption, TimeSpan)

使用指定的逾時值和需求,初始化 TransactionScope 類別的新執行個體。

TransactionScope(TransactionScopeOption, TimeSpan, TransactionScopeAsyncFlowOption)

使用指定的逾時值、需求和非同步流程選項,初始化 TransactionScope 類別的新執行個體。

TransactionScope(TransactionScopeOption, TransactionOptions)

使用指定的需求,初始化 TransactionScope 類別的新執行個體。

TransactionScope(TransactionScopeOption, TransactionOptions, EnterpriseServicesInteropOption)

使用指定的範圍和 COM+ 互通性需求,以及異動選項,初始化 TransactionScope 類別的新執行個體。

TransactionScope(TransactionScopeOption, TransactionOptions, TransactionScopeAsyncFlowOption)

[在 .NET Framework 4.5.1 及更新版本中支援]

使用指定的需求和非同步流程選項,初始化 TransactionScope 類別的新執行個體。

TransactionScope(TransactionScopeOption, TransactionScopeAsyncFlowOption)

使用指定的需求和非同步流程選項,初始化 TransactionScope 類別的新執行個體。

方法

Complete()

表示範圍內的所有作業都已成功完成。

Dispose()

結束交易範圍。

Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
GetHashCode()

做為預設雜湊函式。

(繼承來源 Object)
GetType()

取得目前執行個體的 Type

(繼承來源 Object)
MemberwiseClone()

建立目前 Object 的淺層複製。

(繼承來源 Object)
ToString()

傳回代表目前物件的字串。

(繼承來源 Object)

適用於

執行緒安全性

此型別具備執行緒安全。

另請參閱