TransactionScope TransactionScope TransactionScope TransactionScope Class

정의

트랜잭션 코드 블록을 만듭니다.Makes a code block transactional. 이 클래스는 상속될 수 없습니다.This class cannot be inherited.

public ref class TransactionScope sealed : IDisposable
public sealed class TransactionScope : IDisposable
type TransactionScope = class
    interface IDisposable
Public NotInheritable Class TransactionScope
Implements IDisposable
상속
TransactionScopeTransactionScopeTransactionScopeTransactionScope
구현

예제

다음 예제에서는 사용 하는 방법에 설명 합니다 TransactionScope 트랜잭션에 참여 하는 코드 블록을 정의 하는 클래스입니다.The following example demonstrates how to use the TransactionScope class to define a block of code to participate in a transaction.

// 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 트랜잭션을 관리 하는 자동으로 인프라에서 클래스입니다.The System.Transactions infrastructure provides both an explicit programming model based on the Transaction class, as well as an implicit programming model using the TransactionScope class, in which transactions are automatically managed by the infrastructure.

중요

사용 하 여 암시적 트랜잭션을 만드는 것이 좋습니다는 TransactionScope 클래스에 앰비언트 트랜잭션 컨텍스트가 자동으로 관리 되도록 합니다.We recommend that you create implicit transactions using the TransactionScope class, so that the ambient transaction context is automatically managed for you. 또한 사용 해야 합니다 TransactionScopeDependentTransaction 여러 함수 호출이 나 여러 스레드 호출에서 동일한 트랜잭션의 사용을 해야 하는 애플리케이션에 대 한 클래스입니다.You should also use the TransactionScope and DependentTransaction class for applications that require the use of the same transaction across multiple function calls or multiple thread calls. 이 모델에 대 한 자세한 내용은 참조는 구현 하는 암시적 트랜잭션을 사용 하 여 트랜잭션 범위 항목입니다.For more information on this model, see the Implementing An Implicit Transaction Using Transaction Scope topic. 트랜잭션 애플리케이션 작성에 대 한 자세한 내용은 참조 하세요. 쓰기는 트랜잭션 애플리케이션합니다.For more information on writing a transactional application, see Writing A Transactional Application.

인스턴스화 시를 TransactionScope 여는 new 문에서 트랜잭션 관리자에 참여할 트랜잭션을 결정 합니다.Upon instantiating a TransactionScope by the new statement, the transaction manager determines which transaction to participate in. 일단 결정되면 범위는 항상 해당 트랜잭션에 참여합니다.Once determined, the scope always participates in that transaction. 앰비언트 트랜잭션이 있는지 여부와 생성자에 있는 TransactionScopeOption 매개 변수의 값에 따라 참여할 트랜잭션이 결정됩니다.The decision is based on two factors: whether an ambient transaction is present and the value of the TransactionScopeOption parameter in the constructor. 앰비언트 트랜잭션은 매우 코드에서 실행 되는 트랜잭션입니다.The ambient transaction is the transaction your code executes in. Transaction.Current 클래스의 정적 Transaction 속성을 호출하여 앰비언트 트랜잭션에 대한 참조를 가져올 수 있습니다.You can obtain a reference to the ambient transaction by calling the static Transaction.Current property of the Transaction class. 이 매개 변수를 사용 하는 방법에 대 한 자세한 내용은 "트랜잭션 흐름 관리" 섹션을 참조 합니다 구현 하는 암시적 트랜잭션을 사용 하 여 트랜잭션 범위 항목입니다.For more information on how this parameter is used, see the "Transaction Flow Management" section of the Implementing An Implicit Transaction Using Transaction Scope topic.

트랜잭션 범위 내에서 예외가 발생 하는 경우 (즉, 초기화 간의 TransactionScope 개체와의 호출을 해당 Dispose 메서드), 범위 참여 하는 트랜잭션이 진행을 허용 합니다.If no exception occurs within the transaction scope (that is, between the initialization of the TransactionScope object and the calling of its Dispose method), then the transaction in which the scope participates is allowed to proceed. 트랜잭션 범위 내에서 예외가 발생할 경우 참여 하는 트랜잭션이 롤백됩니다.If an exception does occur within the transaction scope, the transaction in which it participates will be rolled back.

트랜잭션에서 수행 하려는 애플리케이션에 모든 작업이 완료 될 때 호출 해야 합니다는 Complete 메서드는 트랜잭션 커밋이 허용 되었음을 해당 트랜잭션 관리자에 게 알리는를 한 번만 합니다.When your application completes all work it wants to perform in a transaction, you should call the Complete method only once to inform that transaction manager that it is acceptable to commit the transaction. 이 메서드를 호출 하지 못하면 트랜잭션을 중단 합니다.Failing to call this method aborts the transaction.

에 대 한 호출을 Dispose 메서드 트랜잭션 범위의 끝을 표시 합니다.A call to the Dispose method marks the end of the transaction scope. 이 메서드를 호출한 후에 발생하는 예외는 트랜잭션에 영향을 주지 않습니다.Exceptions that occur after calling this method may not affect the transaction.

값을 수정 하는 경우 Current 범위 내에서 예외가 throw 됩니다 때 Dispose 라고 합니다.If you modify the value of Current inside a scope, an exception is thrown when Dispose is called. 그러나 범위 끝 이전 값이 복원 됩니다.However, at the end of the scope, the previous value is restored. 또한 호출 하는 경우 Dispose 에서 Current 트랜잭션을 생성 하는 트랜잭션 범위 내에서 범위의 끝에서 트랜잭션이 중단 됩니다.In addition, if you call Dispose on Current inside a transaction scope that created the transaction, the transaction aborts at the end of the scope.

생성자

TransactionScope() TransactionScope() TransactionScope() TransactionScope()

TransactionScope 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the TransactionScope class.

TransactionScope(Transaction) TransactionScope(Transaction) TransactionScope(Transaction) TransactionScope(Transaction)

TransactionScope 클래스의 새 인스턴스를 초기화하고 지정된 트랜잭션을 앰비언트 트랜잭션으로 설정하여 범위에서 수행된 트랜잭션 작업에 이 트랜잭션을 사용합니다.Initializes a new instance of the TransactionScope class and sets the specified transaction as the ambient transaction, so that transactional work done inside the scope uses this transaction.

TransactionScope(Transaction, TimeSpan) TransactionScope(Transaction, TimeSpan) TransactionScope(Transaction, TimeSpan) TransactionScope(Transaction, TimeSpan)

지정된 시간 제한 값을 가진 TransactionScope 클래스의 새 인스턴스를 초기화하고, 범위에서 수행된 트랜잭션 작업에 이 트랜잭션이 사용되도록 지정된 트랜잭션을 앰비언트 트랜잭션으로 설정합니다.Initializes a new instance of the TransactionScope class with the specified timeout value, and sets the specified transaction as the ambient transaction, so that transactional work done inside the scope uses this transaction.

TransactionScope(Transaction, TimeSpan, EnterpriseServicesInteropOption) TransactionScope(Transaction, TimeSpan, EnterpriseServicesInteropOption) TransactionScope(Transaction, TimeSpan, EnterpriseServicesInteropOption) TransactionScope(Transaction, TimeSpan, EnterpriseServicesInteropOption)

지정된 시간 제한 값과 COM+ 상호 운용성 요구 사항을 가진 TransactionScope 클래스의 새 인스턴스를 초기화하고, 범위에서 수행된 트랜잭션 작업에 이 트랜잭션이 사용되도록 지정된 트랜잭션을 앰비언트 트랜잭션으로 설정합니다.Initializes a new instance of the TransactionScope class with the specified timeout value and COM+ interoperability requirements, and sets the specified transaction as the ambient transaction, so that transactional work done inside the scope uses this transaction.

TransactionScope(Transaction, TimeSpan, TransactionScopeAsyncFlowOption) TransactionScope(Transaction, TimeSpan, TransactionScopeAsyncFlowOption) TransactionScope(Transaction, TimeSpan, TransactionScopeAsyncFlowOption) TransactionScope(Transaction, TimeSpan, TransactionScopeAsyncFlowOption)

[.NET Framework 4.5.1 이상 버전에서 지원됨][Supported in the .NET Framework 4.5.1 and later versions] 지정된 시간 제한 값을 가진 TransactionScope 클래스의 새 인스턴스를 초기화하고, 범위에서 수행된 트랜잭션 작업에 이 트랜잭션이 사용되도록 지정된 트랜잭션을 앰비언트 트랜잭션으로 설정합니다.Initializes a new instance of the TransactionScope class with the specified timeout value, and sets the specified transaction as the ambient transaction, so that transactional work done inside the scope uses this transaction.

TransactionScope(Transaction, TransactionScopeAsyncFlowOption) TransactionScope(Transaction, TransactionScopeAsyncFlowOption) TransactionScope(Transaction, TransactionScopeAsyncFlowOption) TransactionScope(Transaction, TransactionScopeAsyncFlowOption)

[.NET Framework 4.5.1 이상 버전에서 지원됨][Supported in the .NET Framework 4.5.1 and later versions] TransactionScope 클래스의 새 인스턴스를 초기화하고 지정된 트랜잭션을 앰비언트 트랜잭션으로 설정하여 범위에서 수행된 트랜잭션 작업에 이 트랜잭션을 사용합니다.Initializes a new instance of the TransactionScope class and sets the specified transaction as the ambient transaction, so that transactional work done inside the scope uses this transaction.

TransactionScope(TransactionScopeAsyncFlowOption) TransactionScope(TransactionScopeAsyncFlowOption) TransactionScope(TransactionScopeAsyncFlowOption) TransactionScope(TransactionScopeAsyncFlowOption)

지정된 비동기 흐름 옵션을 사용하여 TransactionScope 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the TransactionScope class with the specified asynchronous flow option.

TransactionScope(TransactionScopeOption) TransactionScope(TransactionScopeOption) TransactionScope(TransactionScopeOption) TransactionScope(TransactionScopeOption)

지정된 요구 사항에 따라 TransactionScope 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the TransactionScope class with the specified requirements.

TransactionScope(TransactionScopeOption, TimeSpan) TransactionScope(TransactionScopeOption, TimeSpan) TransactionScope(TransactionScopeOption, TimeSpan) TransactionScope(TransactionScopeOption, TimeSpan)

지정된 시간 제한 값과 요구 사항을 가진 TransactionScope 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the TransactionScope class with the specified timeout value and requirements.

TransactionScope(TransactionScopeOption, TimeSpan, TransactionScopeAsyncFlowOption) TransactionScope(TransactionScopeOption, TimeSpan, TransactionScopeAsyncFlowOption) TransactionScope(TransactionScopeOption, TimeSpan, TransactionScopeAsyncFlowOption) TransactionScope(TransactionScopeOption, TimeSpan, TransactionScopeAsyncFlowOption)

지정된 제한 시간 값, 요구 사항 및 비동기 흐름 옵션을 사용하여 TransactionScope 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the TransactionScope class with the specified timeout value, requirements, and asynchronous flow option.

TransactionScope(TransactionScopeOption, TransactionOptions) TransactionScope(TransactionScopeOption, TransactionOptions) TransactionScope(TransactionScopeOption, TransactionOptions) TransactionScope(TransactionScopeOption, TransactionOptions)

지정된 요구 사항에 따라 TransactionScope 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the TransactionScope class with the specified requirements.

TransactionScope(TransactionScopeOption, TransactionOptions, EnterpriseServicesInteropOption) TransactionScope(TransactionScopeOption, TransactionOptions, EnterpriseServicesInteropOption) TransactionScope(TransactionScopeOption, TransactionOptions, EnterpriseServicesInteropOption) TransactionScope(TransactionScopeOption, TransactionOptions, EnterpriseServicesInteropOption)

지정된 범위, COM+ 상호 운용성 요구 사항 및 트랜잭션 옵션을 가진 TransactionScope 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the TransactionScope class with the specified scope and COM+ interoperability requirements, and transaction options.

TransactionScope(TransactionScopeOption, TransactionOptions, TransactionScopeAsyncFlowOption) TransactionScope(TransactionScopeOption, TransactionOptions, TransactionScopeAsyncFlowOption) TransactionScope(TransactionScopeOption, TransactionOptions, TransactionScopeAsyncFlowOption) TransactionScope(TransactionScopeOption, TransactionOptions, TransactionScopeAsyncFlowOption)

[.NET Framework 4.5.1 이상 버전에서 지원됨][Supported in the .NET Framework 4.5.1 and later versions] 지정된 요구 사항 및 비동기 흐름 옵션을 사용해서 TransactionScope 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the TransactionScope class with the specified requirements and asynchronous flow option.

TransactionScope(TransactionScopeOption, TransactionScopeAsyncFlowOption) TransactionScope(TransactionScopeOption, TransactionScopeAsyncFlowOption) TransactionScope(TransactionScopeOption, TransactionScopeAsyncFlowOption) TransactionScope(TransactionScopeOption, TransactionScopeAsyncFlowOption)

지정된 요구 사항 및 비동기 흐름 옵션을 사용해서 TransactionScope 클래스의 새 인스턴스를 초기화합니다.Initializes a new instance of the TransactionScope class with the specified requirements and asynchronous flow option.

메서드

Complete() Complete() Complete() Complete()

범위의 모든 작업이 성공적으로 완료되었음을 나타냅니다.Indicates that all operations within the scope are completed successfully.

Dispose() Dispose() Dispose() Dispose()

트랜잭션 범위를 종료합니다.Ends the transaction scope.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

지정한 개체와 현재 개체가 같은지 여부를 확인합니다.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

기본 해시 함수로 작동합니다.Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

현재 인스턴스의 Type을 가져옵니다.Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

현재 개체를 나타내는 문자열을 반환합니다.Returns a string that represents the current object.

(Inherited from Object)

적용 대상

스레드 보안

이 형식은 스레드로부터 안전합니다.This type is thread safe.

추가 정보