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분
정성태

... 16  17  18  19  20  21  22  23  24  25  26  27  28  29  [30]  ...
NoWriterDateCnt.TitleFile(s)
12871정성태12/12/20217460오류 유형: 771. docker: Error response from daemon: OCI runtime create failed
12870정성태12/9/20216066개발 환경 구성: 614. 파이썬 - PyPI 패키지 만들기 (4) package_data 옵션
12869정성태12/8/20218272개발 환경 구성: 613. git clone 실행 시 fingerprint 묻는 단계를 생략하는 방법
12868정성태12/7/20216840오류 유형: 770. twine 업로드 시 "HTTPError: 400 Bad Request ..." 오류 [1]
12867정성태12/7/20216547개발 환경 구성: 612. 파이썬 - PyPI 패키지 만들기 (3) entry_points 옵션
12866정성태12/7/202113919오류 유형: 769. "docker build ..." 시 "failed to solve with frontend dockerfile.v0: failed to read dockerfile ..." 오류
12865정성태12/6/20216614개발 환경 구성: 611. 파이썬 - PyPI 패키지 만들기 (2) long_description, cmdclass 옵션
12864정성태12/6/20215088Linux: 46. WSL 환경에서 find 명령을 사용해 파일을 찾는 방법
12863정성태12/4/20216987개발 환경 구성: 610. 파이썬 - PyPI 패키지 만들기
12862정성태12/3/20215730오류 유형: 768. Golang - 빌드 시 "cmd/go: unsupported GOOS/GOARCH pair linux /amd64" 오류
12861정성태12/3/20217953개발 환경 구성: 609. 파이썬 - "Windows embeddable package"로 개발 환경 구성하는 방법
12860정성태12/1/20216058오류 유형: 767. SQL Server - 127.0.0.1로 접속하는 경우 "Access is denied"가 발생한다면?
12859정성태12/1/202112208개발 환경 구성: 608. Hyper-V 가상 머신에 Console 모드로 로그인하는 방법
12858정성태11/30/20219463개발 환경 구성: 607. 로컬의 USB 장치를 원격 머신에 제공하는 방법 - usbip-win
12857정성태11/24/20216959개발 환경 구성: 606. WSL Ubuntu 20.04에서 파이썬을 위한 uwsgi 설치 방법
12856정성태11/23/20218742.NET Framework: 1121. C# - 동일한 IP:Port로 바인딩 가능한 서버 소켓 [2]
12855정성태11/13/20216138개발 환경 구성: 605. Azure App Service - Kudu SSH 환경에서 FTP를 이용한 파일 전송
12854정성태11/13/20217676개발 환경 구성: 604. Azure - 윈도우 VM에서 FTP 여는 방법
12853정성태11/10/20216059오류 유형: 766. Azure App Service - JBoss 호스팅 생성 시 "This region has quota of 0 PremiumV3 instances for your subscription. Try selecting different region or SKU."
12851정성태11/1/20217369스크립트: 34. 파이썬 - MySQLdb 기본 예제 코드
12850정성태10/27/20218520오류 유형: 765. 우분투에서 pip install mysqlclient 실행 시 "OSError: mysql_config not found" 오류
12849정성태10/17/20217689스크립트: 33. JavaScript와 C#의 시간 변환 [1]
12848정성태10/17/20218646스크립트: 32. 파이썬 - sqlite3 기본 예제 코드 [1]
12847정성태10/14/20218487스크립트: 31. 파이썬 gunicorn - WORKER TIMEOUT 오류 발생
12846정성태10/7/20218256스크립트: 30. 파이썬 __debug__ 플래그 변수에 따른 코드 실행 제어
12845정성태10/6/20218097.NET Framework: 1120. C# - BufferBlock<T> 사용 예제 [5]파일 다운로드1
... 16  17  18  19  20  21  22  23  24  25  26  27  28  29  [30]  ...