Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일

TransactionScope에 사용자 정의 트랜잭션을 참여시키는 방법

오호~~~ 12월 6일 주간 닷넷에,

주간닷넷 2016년 12월 6일
; https://learn.microsoft.com/en-us/archive/blogs/eva/주간닷넷-2016년-12월-6일

재미난 글이 나왔군요. ^^

Let .NET framework care about transactions handling for you by implementing IEnlistmentNotification
; https://blog.goyello.com/2016/11/30/let-net-framework-care-about-transactions-handling-for-you-by-implementing-ienlistmentnotification/

바로 TransactionScope에 간이 사용자 정의 트랜잭션을 끼워 넣을 수 있는 IEnlistmentNotification 인터페이스에 대한 소개입니다.

IEnlistmentNotification
; https://learn.microsoft.com/en-us/dotnet/api/system.transactions.ienlistmentnotification

방법이 생각보다 간단합니다. 그냥 다음과 같이 인터페이스를 구현해 주고, 적당하게 트랜잭션 단계마다 필요한 작업만 해주면 됩니다.

using System;
using System.Transactions;

class TxObject : IEnlistmentNotification
{
    public TxObject(object objValue)
    {
        if (Transaction.Current != null)
        {
            Transaction.Current.EnlistVolatile(this, EnlistmentOptions.None);
        }
    }

    public void Commit(Enlistment enlistment)
    {
        enlistment.Done();
    }

    public void InDoubt(Enlistment enlistment)
    {
        enlistment.Done();
    }

    public void Prepare(PreparingEnlistment preparingEnlistment)
    {
        preparingEnlistment.Prepared(); // or, preparingEnlistment.ForceRollback();
    }

    public void Rollback(Enlistment enlistment)
    {
        enlistment.Done();
    }
}

class Program
{
    static void Main(string[] args)
    {
        using (var tx = new TransactionScope())
        {
            TxObject obj = new TxObject(null);

            tx.Complete();
        }
    }
}

예를 하나 들어볼까요? 가령, 웹 사이트에서 게시판 구현할 때 DB에 게시글 정보를 저장한 후 첨부 파일도 처리할 때가 종종 있습니다. 이럴 때, DB 저장과 첨부 파일 저장을 하나의 트랜잭션으로 묶는 것을 고려할 수 있습니다. 물론, 정확하게 구현하려면 이런 경우 비스타 운영체제부터 지원하는 TxF(Transactional NTFS) 기능을 이용해야 하는데,

Transactional NTFS (TxF) .NET
; https://txfnet.codeplex.com/

그냥 가볍게 다음과 같은 식으로 구현하는 것도 가능합니다.

using System;
using System.IO;
using System.Transactions;

class TxFile : IEnlistmentNotification
{
    string _savedPath;
    string _orgFilePath;
    string _contents;

    public TxFile(string filePath, string contents)
    {
        _orgFilePath = filePath;
        _savedPath = filePath;
        _contents = contents;

        if (Transaction.Current != null)
        {
            _savedPath = string.Format("{0}.in_tx", filePath);
            Transaction.Current.EnlistVolatile(this, EnlistmentOptions.None);
        }
        else
        {
            File.WriteAllText(_orgFilePath, _contents);
        }
    }

    public void Commit(Enlistment enlistment)
    {
        File.Move(_savedPath, _orgFilePath);
        enlistment.Done();
    }

    public void InDoubt(Enlistment enlistment)
    {
        enlistment.Done();
    }

    public void Prepare(PreparingEnlistment preparingEnlistment)
    {
        preparingEnlistment.Prepared();
    }

    public void Rollback(Enlistment enlistment)
    {
        if (File.Exists(_savedPath))
        {
            File.Delete(_savedPath);
        }

        enlistment.Done();
    }

    public void Save()
    {
        File.WriteAllText(_savedPath, _contents);
    }
}

class Program
{
    static void Main(string[] args)
    {
        string filePath = "c:\\temp\\test.txt";

        using (var tx = new TransactionScope())
        {
            // ... [트랜잭션에 참여하는 SQL 코드 생략] ...

            TxFile file = new TxFile(filePath, "test is good");
            file.Save();

            // throw new ApplicationException("Exception occurred!");

            tx.Complete();
        }
    }
}

위의 코드를 실행해 보면, tx.Complete(); 시점에 정상적으로 파일이 생성되는 반면 중간에 "// throw ..." 주석을 해제하거나 tx.Complete() 호출을 제거하면 Rollback 메서드의 호출로 인해 파일이 삭제가 됩니다.

물론, TxF(Transactional NTFS)만큼 정교한 트랜잭션을 구현하려면 트랜잭션 로그 파일도 기록하는 등의 작업도 해야 하지만 그럴 거면 차라리 TxF를 사용하는 것이 더 낫습니다.



그러고 보니, 예전에 Python에서 __enter__, __exit__ 기능을 활용한 with 문 구현에서 "값 변경에 따른 트랜잭션 구현"을 설명한 적이 있는데요.

Python의 zip과 with 문 context를 C#과 비교하면.
; https://www.sysnet.pe.kr/2/0/1371

이것도 다음과 같은 식으로 유사하게 구현해 볼 수 있습니다.

public class ValueTransaction<T> : IEnlistmentNotification
{
    T _orgValue;
    T _value;
    public T Value { get { return _value; } }

    public ValueTransaction(T value)
    {
        _orgValue = value;
        _value = value;

        if (Transaction.Current != null)
        {
            Transaction.Current.EnlistVolatile(this, EnlistmentOptions.None);
        }
    }

    public void SetValue(T newValue)
    {
        _value = newValue;
    }

    public void Commit(Enlistment enlistment)
    {
        enlistment.Done();
    }

    public void InDoubt(Enlistment enlistment)
    {
        enlistment.Done();
    }

    public void Prepare(PreparingEnlistment preparingEnlistment)
    {
        preparingEnlistment.Prepared(); // or preparingEnlistment.ForceRollback();
    }

    public void Rollback(Enlistment enlistment)
    {
        _value = _orgValue;
        enlistment.Done();
    }
}

class Program
{
    static void Main(string[] args)
    {
        ValueTransaction<int> myValue = null;

        try
        {
            using (var tx = new TransactionScope())
            {
                myValue = new ValueTransaction<int>(6);
                myValue.SetValue(5);

                // throw new ApplicationException("TEST");

                tx.Complete();
            }
        } catch { }

        if (myValue != null)
        {
            Console.WriteLine(myValue.Value);
        }
    }
}

뭐,,, 대충 비슷한가요? ^^

(첨부 파일은 본문의 예제 코드를 포함합니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 5/31/2023]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2017-01-09 03시05분
정성태
2017-01-09 03시36분
정성태

... 31  32  33  34  35  36  37  38  39  [40]  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
12620정성태4/29/202111915.NET Framework: 1052. C# - 왜 구조체는 16 바이트의 크기가 적합한가? [1]파일 다운로드1
12619정성태4/28/202112404.NET Framework: 1051. C# - 구조체의 크기가 16바이트가 넘어가면 힙에 할당된다? [2]파일 다운로드1
12618정성태4/27/202110964사물인터넷: 58. NodeMCU v1 ESP8266 CP2102 Module을 이용한 WiFi UDP 통신 [1]파일 다운로드1
12617정성태4/26/20218628.NET Framework: 1050. C# - ETW EventListener의 Keywords별 EventId에 따른 필터링 방법파일 다운로드1
12616정성태4/26/20218606.NET Framework: 1049. C# - ETW EventListener를 상속받았을 때 초기화 순서파일 다운로드1
12615정성태4/26/20216785오류 유형: 712. Microsoft Live 로그인 - 계정을 선택하는(Pick an account) 화면에서 진행이 안 되는 문제
12614정성태4/24/20219457개발 환경 구성: 570. C# - Azure AD 인증을 지원하는 ASP.NET Core/5+ 웹 애플리케이션 예제 구성 [4]파일 다운로드1
12613정성태4/23/20218524.NET Framework: 1048. C# - ETW 이벤트의 Keywords에 속한 EventId 구하는 방법 (2) 관리 코드파일 다운로드1
12612정성태4/23/20218619.NET Framework: 1047. C# - ETW 이벤트의 Keywords에 속한 EventId 구하는 방법 (1) PInvoke파일 다운로드1
12611정성태4/22/20217916오류 유형: 711. 닷넷 EXE 실행 오류 - Mixed mode assembly is build against version 'v2.0.50727' of the runtime
12610정성태4/22/20217732.NET Framework: 1046. C# - 컴파일 시점에 참조할 수 없는 타입을 포함한 이벤트 핸들러를 Reflection을 이용해 구독하는 방법파일 다운로드1
12609정성태4/22/20219016.NET Framework: 1045. C# - 런타임 시점에 이벤트 핸들러를 만들어 Reflection을 이용해 구독하는 방법파일 다운로드1
12608정성태4/21/202110041.NET Framework: 1044. C# - Generic Host를 이용해 .NET 5로 리눅스 daemon 프로그램 만드는 방법 [9]파일 다운로드1
12607정성태4/21/20218568.NET Framework: 1043. C# - 실행 시점에 동적으로 Delegate 타입을 만드는 방법파일 다운로드1
12606정성태4/21/202112449.NET Framework: 1042. C# - enum 값을 int로 암시적(implicit) 형변환하는 방법? [2]파일 다운로드1
12605정성태4/18/20218530.NET Framework: 1041. C# - AssemblyID, ModuleID를 관리 코드에서 구하는 방법파일 다운로드1
12604정성태4/18/20217312VS.NET IDE: 163. 비주얼 스튜디오 속성 창의 "Build(빌드)" / "Configuration(구성)"에서의 "활성" 의미
12603정성태4/16/20218152VS.NET IDE: 162. 비주얼 스튜디오 - 상속받은 컨트롤이 디자인 창에서 지원되지 않는 문제
12602정성태4/16/20219345VS.NET IDE: 161. x64 DLL 프로젝트의 컨트롤이 Visual Studio의 Designer에서 보이지 않는 문제 [1]
12601정성태4/15/20218453.NET Framework: 1040. C# - REST API 대신 github 클라이언트 라이브러리를 통해 프로그래밍으로 접근
12600정성태4/15/20218635.NET Framework: 1039. C# - Kubeconfig의 token 설정 및 인증서 구성을 자동화하는 프로그램
12599정성태4/14/20219338.NET Framework: 1038. C# - 인증서 및 키 파일로부터 pfx/p12 파일을 생성하는 방법파일 다운로드1
12598정성태4/14/20219481.NET Framework: 1037. openssl의 PEM 개인키 파일을 .NET RSACryptoServiceProvider에서 사용하는 방법 (2)파일 다운로드1
12597정성태4/13/20219495개발 환경 구성: 569. csproj의 내용을 공통 설정할 수 있는 Directory.Build.targets / Directory.Build.props 파일
12596정성태4/12/20219287개발 환경 구성: 568. Windows의 80 포트 점유를 해제하는 방법
12595정성태4/12/20218689.NET Framework: 1036. SQL 서버 - varbinary 타입에 대한 문자열의 CAST, CONVERT 변환을 C# 코드로 구현
... 31  32  33  34  35  36  37  38  39  [40]  41  42  43  44  45  ...