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 暗黙的なトランザクションを作成することをお勧めします。 また、複数の関数呼び出しまたは複数のスレッド呼び出しで同じトランザクションを使用する必要があるアプリケーションには、 クラスと DependentTransaction クラスも使用TransactionScopeする必要があります。 このモデルの詳細については、「 トランザクション スコープを使用した暗黙的なトランザクションの実装 」トピックを参照してください。 トランザクション アプリケーションの記述の詳細については、「トランザクション アプリケーションの 作成」を参照してください。

ステートメントによって newTransactionScopeインスタンス化すると、トランザクション マネージャーによって、参加するトランザクションが決定されます。 いったん決定されると、このスコープは常にそのトランザクションに参加します。 この決定は 2 つの要因に基づいて行われます。1 つはアンビエント トランザクションが存在するかどうか、もう 1 つはコンストラクターの TransactionScopeOption パラメーターの値です。 アンビエント トランザクションは、コードが実行するトランザクションです。 Transaction.Current クラスの静的 Transaction プロパティを呼び出すことによってアンビエント トランザクションへの参照を取得できます。 このパラメーターの使用方法の詳細については、「トランザクション スコープを使用した暗黙的な トランザクションの実装」トピックの「トランザクション フロー管理」セクションを参照してください。

トランザクション スコープ内で例外が発生しない場合 (つまり、オブジェクトの初期化とそのメソッドの TransactionScope 呼び出しの Dispose 間)、スコープが参加しているトランザクションの続行が許可されます。 トランザクション スコープ内で例外が発生した場合は、その例外が参加しているトランザクションがロールバックされます。

アプリケーションがトランザクションで実行するすべての作業を完了したら、 メソッドを 1 回だけ呼び出して Complete 、トランザクションマネージャーにトランザクションのコミットが可能であることを通知する必要があります。 このメソッドの呼び出しに失敗すると、トランザクションが中止されます。

メソッドを呼び出すと、 Dispose トランザクション スコープの末尾がマークされます。 このメソッドの呼び出し後に発生した例外は、トランザクションに影響しない場合があります。

スコープ内の の Current 値を変更すると、 が呼び出されたときに例外が Dispose スローされます。 ただし、スコープの最後に、前の値が復元されます。 さらに、トランザクションを作成したトランザクション スコープ内で をCurrent呼び出Disposeすと、トランザクションはスコープの末尾で中止されます。

コンストラクター

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)

適用対象

スレッド セーフ

この型はスレッド セーフです。

こちらもご覧ください