Microsoft MVP성태의 닷넷 이야기
.NET Framework: 347. C# - 프로세스(EXE) 수준의 Singleton 개체 생성 [링크 복사], [링크+제목 복사],
조회: 27031
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 2개 있습니다.)

C# - 프로세스(EXE) 수준의 Singleton 개체 생성

운영체제에 의해서 프로세스 격리가 제공되는 것을, 닷넷은 다시 프로세스 내부를 AppDomain이라는 단위로 격리시키고 서로 간의 직접 접근이 불가능하도록 만들었습니다.

그래서, Native 언어(예: C/C++)에서는 static으로 singleton을 만들었던 것을 닷넷에서는 static으로 지정했다고 프로세스 전역적으로 한 개만 존재하지는 않습니다, AppDomain 별로 존재하는 것이지.

이에 대한 해결책을 다음의 글에서 제공하고 있습니다.

Cross AppDomain Singleton 
; http://ingebrigtsen.info/2007/05/18/cross-appdomain-singleton/

근데, 코드가 별로 마음에 안 듭니다. ^^ Interop DLL이 별도로 추가된다는 것은 관리적인 요소만 하나 더 늘리게 되는 요인이 됩니다. 그래서, 아래의 방법을 곁들이면 더 좋습니다. ^^

레지스트리 등록 및 Interop DLL 없이 COM 개체 사용하는 방법
; https://www.sysnet.pe.kr/2/0/1180

public class CrossAppDomainSingleton<T> : MarshalByRefObject where T : new()
{
	...[생략]...
    private static AppDomain GetAppDomain(string friendlyName)
    {
        IntPtr enumHandle = IntPtr.Zero;
        ICorRuntimeHost host = null;

        try
        {
            host = Utility.CoCreateInstance("{CB2F6723-AB3A-11D2-9C40-00C04FA30A3E}") as ICorRuntimeHost;

            if (host == null)
            {
                return null;
            }

            host.EnumDomains(out enumHandle);

            object domain = null;
            while (true)
            {
                host.NextDomain(enumHandle, out domain);
                if (domain == null)
                {
                    break;
                }
                AppDomain appDomain = (AppDomain)domain;
                if (appDomain.FriendlyName.Equals(friendlyName))
                {
                    return appDomain;
                }
            }
        }
        finally
        {
            host.CloseEnum(enumHandle);
            Marshal.ReleaseComObject(host);
            host = null;
        }
        return null;
    }

	...[생략]...
}

지면(?) 관계상 ICorRuntimeHost 등의 구현은 이 글의 첨부 파일로 참고하시면 됩니다.

그나저나, 어쩔 수 없이 프로세스 수준의 Singleton을 사용해야 하지만 성능 손실은 과연 어느 정도일까요? 이를 위해 다음과 같이 테스트 코드를 작성해 봤습니다.

public static class NonSingleton
{
    static bool _test = true;
    public static bool Test { get { return _test; } }
}

public class Singleton : CrossAppDomainSingleton<Singleton>
{
    bool _test = true;
    public bool Test { get { return _test; } }
}

class Program
{
    static void Main(string[] args)
    {
        CheckTime(false, 1); // JIT 컴파일 시간을 배제하기 위해.
        CheckTime(true, 1000000);
    }

    private static void CheckTime(bool outputResult, int loopCount)
    {
        Stopwatch st = new Stopwatch();
        st.Start();

        int inc = 0;
        for (int i = 0; i < loopCount; i++)
        {
            if (NonSingleton.Test == true)
            {
                inc++;
            }
        }
        st.Stop();

        if (outputResult == true)
        {
            Console.WriteLine(st.ElapsedMilliseconds);
        }

        System.Diagnostics.Trace.WriteLine(inc);

        st.Start();

        inc = 0;
        Singleton singleton = Singleton.Instance;
        for (int i = 0; i < loopCount; i++)
        {
            if (singleton.Test == true)
            {
                inc++;
            }
        }

        st.Stop();

        if (outputResult == true)
        {
            Console.WriteLine(st.ElapsedMilliseconds);
        }

        System.Diagnostics.Trace.WriteLine(inc);
    }
}

Release 빌드 후 테스트 결과는 다음과 같이 나왔습니다.

10,000 번 호출 NonSingleton: 0ms
10,000 번 호출 Singleton: 4ms

100,000 번 호출 NonSingleton: 0ms
100,000 번 호출 Singleton: 45ms

1,000,000 번 호출 NonSingleton: 1ms
1,000,000 번 호출 Singleton: 454ms

10,000,000 번 호출 NonSingleton: 19ms
10,000,000 번 호출 Singleton: 4539ms

거의 200배가 넘게 느린 결과를 볼 수 있는데요. 무척 느리다 싶지만 이런 유의 테스트가 현실로 왔을 때는 재미있게 해석될 수 있습니다. 예를 들어, 1초에 10,000번 호출된다고 가정했을 때 도메인간 호출이 겨우 4ms 더 시간이 걸릴 뿐이므로 그다지 나쁜 결과는 아니라는 것입니다.

** 주의할 점은, 이는 호출 간의 속도 저하일 뿐 마샬링이 복잡해지면 더욱 느려질 수 있다는 사실!!!




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 2/27/2024]

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

비밀번호

댓글 작성자
 



2012-12-06 04시26분
[ryujh] 안녕하세요.

프로세스를 중복실행 방지하기 위해 뮤텍스를 사용하는데 이것이 Singleton 으로 봐도 될지요?

위의 예제는 해본적이 없어서 좀더 보고 질문드리겠습니다.
[guest]
2012-12-06 04시47분
개체가 하나면 싱글턴 개체라고 하는 것처럼, 프로세스가 하나라면 싱글턴 프로세스라는 말을 써도 되겠지요. 싱글턴 프로세스라면 위의 기법을 사용하기보다는 말씀하신 것처럼 뮤텍스가 올바른 선택일 수 있습니다.
정성태

... 61  62  63  64  65  66  67  68  [69]  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12210정성태4/20/202020684.NET Framework: 903. .NET Framework의 Strong-named 어셈블리 바인딩 (1) - app.config을 이용한 바인딩 리디렉션 [1]파일 다운로드1
12209정성태4/13/202017400오류 유형: 614. 리눅스 환경에서 C/C++ 프로그램이 Segmentation fault 에러가 발생한 경우 (2)
12208정성태4/12/202015963Linux: 29. 리눅스 환경에서 C/C++ 프로그램이 Segmentation fault 에러가 발생한 경우
12207정성태4/2/202015791스크립트: 19. Windows PowerShell의 NonInteractive 모드
12206정성태4/2/202018421오류 유형: 613. 파일 잠금이 바로 안 풀린다면? - The process cannot access the file '...' because it is being used by another process.
12205정성태4/2/202015092스크립트: 18. Powershell에서는 cmd.exe의 명령어를 지원하진 않습니다.
12204정성태4/1/202015088스크립트: 17. Powershell 명령어에 ';' (semi-colon) 문자가 포함된 경우
12203정성태3/18/202017932오류 유형: 612. warning: 'C:\ProgramData/Git/config' has a dubious owner: '...'.
12202정성태3/18/202021191개발 환경 구성: 486. .NET Framework 프로젝트를 위한 GitLab CI/CD Runner 구성
12201정성태3/18/202018432오류 유형: 611. git-credential-manager.exe: Using credentials for username "Personal Access Token". [1]
12200정성태3/18/202018520VS.NET IDE: 145. NuGet + Github 라이브러리 디버깅 관련 옵션 3가지 - "Enable Just My Code" / "Enable Source Link support" / "Suppress JIT optimization on module load (Managed only)"
12199정성태3/17/202016166오류 유형: 610. C# - CodeDomProvider 사용 시 Unhandled Exception: System.IO.DirectoryNotFoundException: Could not find a part of the path '...\f2_6uod0.tmp'.
12198정성태3/17/202019527오류 유형: 609. SQL 서버 접속 시 "Cannot open user default database. Login failed."
12197정성태3/17/202018809VS.NET IDE: 144. .NET Core 콘솔 응용 프로그램을 배포(publish) 시 docker image 자동 생성 - 두 번째 이야기 [1]
12196정성태3/17/202015942오류 유형: 608. The ServicedComponent being invoked is not correctly configured (Use regsvcs to re-register).
12195정성태3/16/202018261.NET Framework: 902. C# - 프로세스의 모든 핸들을 열람 - 세 번째 이야기
12194정성태3/16/202020991오류 유형: 607. PostgreSQL - Npgsql.NpgsqlException: sorry, too many clients already
12193정성태3/16/202017903개발 환경 구성: 485. docker - SAP Adaptive Server Enterprise 컨테이너 실행 [1]
12192정성태3/14/202019914개발 환경 구성: 484. docker - Sybase Anywhere 16 컨테이너 실행
12191정성태3/14/202021039개발 환경 구성: 483. docker - OracleXE 컨테이너 실행 [1]
12190정성태3/14/202015617오류 유형: 606. Docker Desktop 업그레이드 시 "The process cannot access the file 'C:\Program Files\Docker\Docker\resources\dockerd.exe' because it is being used by another process."
12189정성태3/13/202021200개발 환경 구성: 482. Facebook OAuth 처리 시 상태 정보 전달 방법과 "유효한 OAuth 리디렉션 URI" 설정 규칙
12188정성태3/13/202026019Windows: 169. 부팅 시점에 실행되는 chkdsk 결과를 확인하는 방법
12187정성태3/12/202015569오류 유형: 605. NtpClient was unable to set a manual peer to use as a time source because of duplicate error on '...'.
12186정성태3/12/202017397오류 유형: 604. The SysVol Permissions for one or more GPOs on this domain controller and not in sync with the permissions for the GPOs on the Baseline domain controller.
12185정성태3/11/202017994오류 유형: 603. The browser service was unable to retrieve a list of servers from the browser master...
... 61  62  63  64  65  66  67  68  [69]  70  71  72  73  74  75  ...