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 여러 함수 호출이 나 여러 스레드 호출에서 동일한 트랜잭션의 사용을 해야 하는 애플리케이션에 대 한 클래스입니다. 이 모델에 대한 자세한 내용은 트랜잭션 범위를 사용하여 암시적 트랜잭션 구현 항목을 참조하세요. 트랜잭션 애플리케이션 작성에 대 한 자세한 내용은 참조 하세요. 쓰기는 트랜잭션 애플리케이션합니다.

문을 통해 newTransactionScope 인스턴스화하면 트랜잭션 관리자가 참여할 트랜잭션을 결정합니다. 일단 결정되면 범위는 항상 해당 트랜잭션에 참여합니다. 이 결정은 두 가지 요인, 즉 앰비언트 트랜잭션이 있는지 여부 및 생성자의 TransactionScopeOption 매개 변수 값을 기반으로 합니다. 앰비언트 트랜잭션은 코드가 실행되는 트랜잭션입니다. Transaction 클래스의 정적 Transaction.Current 속성을 호출하여 앰비언트 트랜잭션에 대한 참조를 가져올 수 있습니다. 이 매개 변수를 사용하는 방법에 대한 자세한 내용은 트랜잭션 범위를 사용하여 암시적 트랜잭션 구현 항목의 "트랜잭션 흐름 관리" 섹션을 참조하세요.

트랜잭션 scope 내에서 예외가 발생하지 않으면(즉, 개체의 TransactionScope 초기화와 메서드 Dispose 호출 사이에) scope 참여하는 트랜잭션을 진행할 수 있습니다. 트랜잭션 scope 내에서 예외가 발생하면 해당 예외가 참여하는 트랜잭션이 롤백됩니다.

트랜잭션에서 수행 하려는 애플리케이션에 모든 작업이 완료 될 때 호출 해야 합니다는 Complete 메서드는 트랜잭션 커밋이 허용 되었음을 해당 트랜잭션 관리자에 게 알리는를 한 번만 합니다. 이 메서드를 호출하지 않으면 트랜잭션이 중단됩니다.

메서드에 대한 호출은 Dispose 트랜잭션 scope 끝을 표시합니다. 이 메서드를 호출한 후에 발생하는 예외는 트랜잭션에 영향을 미치지 않을 수 있습니다.

scope 내에서 값을 Current 수정하면 가 호출되면 예외가 throw Dispose 됩니다. 그러나 scope 끝에 이전 값이 복원됩니다. 또한 트랜잭션을 만든 트랜잭션 scope 내에서 를 Current 호출 Dispose 하면 트랜잭션이 scope 끝에서 중단됩니다.

생성자

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)

적용 대상

스레드 보안

이 형식은 스레드로부터 안전합니다.

추가 정보