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)
12522정성태1/31/20219712개발 환경 구성: 528. 오라클 클라우드의 리눅스 VM - 9000 MTU Jumbo Frame 테스트
12521정성태1/31/20219754개발 환경 구성: 527. 이더넷(Ethernet) 환경의 TCP 통신에서 MSS(Maximum Segment Size) 확인 [1]
12520정성태1/30/20218252개발 환경 구성: 526. 오라클 클라우드의 VM에 ping ICMP 여는 방법
12519정성태1/30/20217381개발 환경 구성: 525. 오라클 클라우드의 VM을 외부에서 접근하기 위해 포트 여는 방법
12518정성태1/30/202124828Linux: 37. Ubuntu에 Wireshark 설치 [2]
12517정성태1/30/202112394Linux: 36. 윈도우 클라이언트에서 X2Go를 이용한 원격 리눅스의 GUI 접속 - 우분투 20.04
12516정성태1/29/20219061Windows: 188. Windows - TCP default template 설정 방법
12515정성태1/28/202110254웹: 41. Microsoft Edge - localhost에 대해 http 접근 시 무조건 https로 바뀌는 문제 [3]
12514정성태1/28/202110562.NET Framework: 1021. C# - 일렉트론 닷넷(Electron.NET) 소개 [1]파일 다운로드1
12513정성태1/28/20218588오류 유형: 698. electronize - User Profile 디렉터리에 공백 문자가 있는 경우 빌드가 실패하는 문제 [1]
12512정성태1/28/20218405오류 유형: 697. The program can't start because VCRUNTIME140.dll is missing from your computer. Try reinstalling the program to fix this problem.
12511정성태1/27/20218142Windows: 187. Windows - 도스 시절의 8.3 경로를 알아내는 방법
12510정성태1/27/20218522.NET Framework: 1020. .NET Core Kestrel 호스팅 - Razor 지원 추가 [1]파일 다운로드1
12509정성태1/27/20219476개발 환경 구성: 524. Jupyter Notebook에서 C#(F#, PowerShell) 언어 사용을 위한 환경 구성 [3]
12508정성태1/27/20218084개발 환경 구성: 523. Jupyter Notebook - Slide 플레이 버튼이 없는 경우
12507정성태1/26/20218193VS.NET IDE: 157. Visual Studio - Syntax Visualizer 메뉴가 없는 경우
12506정성태1/25/202111445.NET Framework: 1019. Microsoft.Tye 기본 사용법 소개 [1]
12505정성태1/23/20219260.NET Framework: 1018. .NET Core Kestrel 호스팅 - Web API 추가 [1]파일 다운로드1
12504정성태1/23/202110376.NET Framework: 1017. .NET 5에서의 네트워크 라이브러리 개선 (2) - HTTP/2, HTTP/3 관련 [1]
12503정성태1/21/20218643오류 유형: 696. C# - HttpClient: Requesting HTTP version 2.0 with version policy RequestVersionExact while HTTP/2 is not enabled.
12502정성태1/21/20219360.NET Framework: 1016. .NET Core HttpClient의 HTTP/2 지원파일 다운로드1
12501정성태1/21/20218437.NET Framework: 1015. .NET 5부터 HTTP/1.1, 2.0 선택을 위한 HttpVersionPolicy 동작 방식파일 다운로드1
12500정성태1/21/20219028.NET Framework: 1014. ASP.NET Core(Kestrel)의 HTTP/2 지원 여부파일 다운로드1
12499정성태1/20/202110254.NET Framework: 1013. .NET Core Kestrel 호스팅 - 포트 변경, non-localhost 접속 지원 및 https 등의 설정 변경 [1]파일 다운로드1
12498정성태1/20/20219206.NET Framework: 1012. .NET Core Kestrel 호스팅 - 비주얼 스튜디오의 Kestrel/IIS Express 프로파일 설정
12497정성태1/20/202110107.NET Framework: 1011. C# - OWIN Web API 예제 프로젝트 [1]파일 다운로드2
... 31  32  33  34  35  36  37  38  39  40  41  42  43  [44]  45  ...