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)
12546정성태3/3/20218337개발 환경 구성: 545. github workflow/actions에서 빌드시 snk 파일 다루는 방법 - Encrypted secrets
12545정성태3/2/202111061.NET Framework: 1026. 닷넷 5에 추가된 POH (Pinned Object Heap) [10]
12544정성태2/26/202111223.NET Framework: 1025. C# - Control의 Invalidate, Update, Refresh 차이점 [2]
12543정성태2/26/20219654VS.NET IDE: 158. C# - 디자인 타임(design-time)과 런타임(runtime)의 코드 실행 구분
12542정성태2/20/202111964개발 환경 구성: 544. github repo의 Release 활성화 및 Actions를 이용한 자동화 방법 [1]
12541정성태2/18/20219232개발 환경 구성: 543. 애저듣보잡 - Github Workflow/Actions 소개
12540정성태2/17/20219534.NET Framework: 1024. C# - Win32 API에 대한 P/Invoke를 대신하는 Microsoft.Windows.CsWin32 패키지
12539정성태2/16/20219427Windows: 189. WM_TIMER의 동작 방식 개요파일 다운로드1
12538정성태2/15/20219847.NET Framework: 1023. C# - GC 힙이 아닌 Native 힙에 인스턴스 생성 - 0SuperComicLib.LowLevel 라이브러리 소개 [2]
12537정성태2/11/202110790.NET Framework: 1022. UI 요소의 접근은 반드시 그 UI를 만든 스레드에서! - 두 번째 이야기 [2]
12536정성태2/9/20219843개발 환경 구성: 542. BDP(Bandwidth-delay product)와 TCP Receive Window
12535정성태2/9/20218965개발 환경 구성: 541. Wireshark로 확인하는 LSO(Large Send Offload), RSC(Receive Segment Coalescing) 옵션
12534정성태2/8/20219588개발 환경 구성: 540. Wireshark + C/C++로 확인하는 TCP 연결에서의 closesocket 동작 [1]파일 다운로드1
12533정성태2/8/20219231개발 환경 구성: 539. Wireshark + C/C++로 확인하는 TCP 연결에서의 shutdown 동작파일 다운로드1
12532정성태2/6/20219761개발 환경 구성: 538. Wireshark + C#으로 확인하는 ReceiveBufferSize(SO_RCVBUF), SendBufferSize(SO_SNDBUF) [3]
12531정성태2/5/20218718개발 환경 구성: 537. Wireshark + C#으로 확인하는 PSH flag와 Nagle 알고리듬파일 다운로드1
12530정성태2/4/202112848개발 환경 구성: 536. Wireshark + C#으로 확인하는 TCP 통신의 Receive Window
12529정성태2/4/20219965개발 환경 구성: 535. Wireshark + C#으로 확인하는 TCP 통신의 MIN RTO [1]
12528정성태2/1/20219346개발 환경 구성: 534. Wireshark + C#으로 확인하는 TCP 통신의 MSS(Maximum Segment Size) - 윈도우 환경
12527정성태2/1/20219585개발 환경 구성: 533. Wireshark + C#으로 확인하는 TCP 통신의 MSS(Maximum Segment Size) - 리눅스 환경파일 다운로드1
12526정성태2/1/20217459개발 환경 구성: 532. Azure Devops의 파이프라인 빌드 시 snk 파일 다루는 방법 - Secure file
12525정성태2/1/20217163개발 환경 구성: 531. Azure Devops - 파이프라인 실행 시 빌드 이벤트를 생략하는 방법
12524정성태1/31/20218224개발 환경 구성: 530. 기존 github 프로젝트를 Azure Devops의 빌드 Pipeline에 연결하는 방법 [1]
12523정성태1/31/20218217개발 환경 구성: 529. 기존 github 프로젝트를 Azure Devops의 Board에 연결하는 방법
12522정성태1/31/20219711개발 환경 구성: 528. 오라클 클라우드의 리눅스 VM - 9000 MTU Jumbo Frame 테스트
12521정성태1/31/20219753개발 환경 구성: 527. 이더넷(Ethernet) 환경의 TCP 통신에서 MSS(Maximum Segment Size) 확인 [1]
... 31  32  33  34  35  36  37  38  39  40  41  42  [43]  44  45  ...