Microsoft MVP성태의 닷넷 이야기
.NET Framework: 180. C# Singleton 인스턴스 생성 [링크 복사], [링크+제목 복사],
조회: 36324
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 5개 있습니다.)
C# Singleton 인스턴스 생성


그러고 보니, Singleton에 대한 글을 몇 개 쓰긴 했군요. ^^

C++에서 싱글톤 구현하기
; https://www.sysnet.pe.kr/2/0/846

DataContext가 thread-safe한 것인가?
; https://www.sysnet.pe.kr/2/0/855

위의 2번째 글에 소개한 링크에서 C#에서의 Singleton 개체 생성에 관한 내용을 확인할 수 있는데요.

C#은 닷넷이 채택한 메모리 모델 덕분에 단순한 DCLP(Double Checked Locking Pattern) 코딩만으로 singleton 개체가 보장됩니다.

static object lockInstance = new object();
static MyObject myInstance;

internal static MyObject Instance
{
    get
    {
        if (myInstance == null)
        {
            lock (lockInstance)
            {
                if (myInstance == null)
                {
                    myInstance = new MyObject();
                }
            }
        }

        return myInstance;
    }           
}

Jeffrey Richter의 "CLR via C#" 책을 보면 현재의 CLR이 채택한 메모리 모델이 그럴 뿐 별도로 누군가? 또는 향후에 다른 운영체제에 구현될 CLR의 메모리 모델이 다른 경우에는 적절한 Memory Barrier를 사용해야 한다고 씌여져 있습니다. (아마도 Mono에서는 그래야 될지도 모르겠습니다.)

역시 "CLR via C#" 책에도 나오지만 대개의 경우 그냥 static 생성자에서 개체를 생성하도록 하는 것이 가장 권장되는 방식이기도 합니다. 저 역시 그렇게 많이 사용하고. ^^

static MyObject myInstance = new MyObject();  // .NET에서는 너무나 간단한 Singleton 개체 생성
                                              // (유의할 점: .NET 런타임에 따라 달라지는 정적 필드의 초기화 유무)

그래도 가끔은 DCLP의 "Lazy Initialization"이 그리울 수도 있을 텐데요. 안전한 static 생성자의 구현 방식에 "Lazy Initialization"을 적용시킨 훌륭한 코드가 "Implementing the Singleton Pattern in C#" 글에서 "Fifth version - fully lazy instantiation" 절에 소개되어 있으니 참고하십시오.




그냥 끝내기 아쉬우니, 잠깐 다소 쓸데없을 것 같은 이야기를 붙여본다면!

결국 Singleton 인스턴스를 생성하는 데에는, 반드시 해당 타입을 한번이라도 접근을 해줘야 하는 것이 중요합니다. 그래서, 때로는 다음과 같이 일부러 빈 static 함수를 만들어 호출해 줄 때도 있습니다.

class MyType
{
    static MyType instance = new MyType();

    public static void Initialize()
    {
    }
}

class Program
{
    static void Main(string[] args)
    {
        MyType.Initialize();
    }
}

처음에 위와 같이 코드를 작성해 보고 내심 걱정이 되었습니다. 왜냐하면, MyType.Initialize 메서드는 아무런 일도 하지 않기 때문에 DEBUG 빌드의 어셈블리를 실행할 때는 잘 될지 모르지만, RELEASE 빌드의 어셈블리를 실행할 때는 최적화로 인해 메서드 호출이 생략될 수 있기 때문입니다.

물론, 테스트를 해보면 결과가 금방 나오는데 MyType 인스턴스는 정상적으로 릴리스 빌드에서도 생성이 됩니다.

오호~~~ 그렇다면 static 메서드에 대해서는 (IL 코드가 없어도) JIT 컴파일러가 반드시 호출을 해주는 걸까요?

그건 또 아닙니다. 위의 MyType.Initialize는 분명히 JIT 컴파일링 되지 않습니다. (CLR Profiler로 확인해 보면 알 수 있습니다.) 하지만 똑똑한 JIT 컴파일러는 Initialize 호출만 생략할 뿐 해당 타입의 cctor까지는 호출해 줍니다. 즉, (RELEASE 빌드) 실행 시에는 다음과 같은 식으로 동작을 하는 것입니다.

class Program
{
    static void Main(string[] args)
    {
        MyType..cctor();   // 사실 이런 식의 호출이 명시적으로 가능했으면 좋겠습니다. 
                           // 쓸데없이 빈 메서드 만들어 줄 필요가 없으니.
        // 혹은, RuntimeHelpers.RunClassConstructor의 힘을 빌려도 되지만 코드가 쓸데없이 어려운 듯한 분위기를 풍깁니다. ^^
    }
}




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 4/3/2023]

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

비밀번호

댓글 작성자
 



2022-06-27 11시35분
Create a lazy-thread-safe-Singleton implementation
; https://dev.to/dotnetsafer/these-5-c-guidelines-revealed-by-a-senior-developer-will-change-your-coding-style-3jfp

public sealed class Singleton
{
    private static readonly Lazy<Singleton> LazyInstance =
    new Lazy<Singleton>(() => new Singleton());
    private Singleton()
    {
    }
    public static Singleton Instance => LazyInstance.Value;
}
정성태
2023-04-28 03시57분
The Need For Volatile with the Double Check Locking Pattern for C#
; https://www.codeproject.com/Tips/887389/Why-You-Should-Use-the-volatile-Keyword-with-the-D
정성태

... 61  62  63  64  65  66  67  68  [69]  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12208정성태4/12/202015942Linux: 29. 리눅스 환경에서 C/C++ 프로그램이 Segmentation fault 에러가 발생한 경우
12207정성태4/2/202015742스크립트: 19. Windows PowerShell의 NonInteractive 모드
12206정성태4/2/202018395오류 유형: 613. 파일 잠금이 바로 안 풀린다면? - The process cannot access the file '...' because it is being used by another process.
12205정성태4/2/202015053스크립트: 18. Powershell에서는 cmd.exe의 명령어를 지원하진 않습니다.
12204정성태4/1/202015061스크립트: 17. Powershell 명령어에 ';' (semi-colon) 문자가 포함된 경우
12203정성태3/18/202017888오류 유형: 612. warning: 'C:\ProgramData/Git/config' has a dubious owner: '...'.
12202정성태3/18/202021154개발 환경 구성: 486. .NET Framework 프로젝트를 위한 GitLab CI/CD Runner 구성
12201정성태3/18/202018387오류 유형: 611. git-credential-manager.exe: Using credentials for username "Personal Access Token". [1]
12200정성태3/18/202018497VS.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/202016130오류 유형: 610. C# - CodeDomProvider 사용 시 Unhandled Exception: System.IO.DirectoryNotFoundException: Could not find a part of the path '...\f2_6uod0.tmp'.
12198정성태3/17/202019515오류 유형: 609. SQL 서버 접속 시 "Cannot open user default database. Login failed."
12197정성태3/17/202018762VS.NET IDE: 144. .NET Core 콘솔 응용 프로그램을 배포(publish) 시 docker image 자동 생성 - 두 번째 이야기 [1]
12196정성태3/17/202015932오류 유형: 608. The ServicedComponent being invoked is not correctly configured (Use regsvcs to re-register).
12195정성태3/16/202018252.NET Framework: 902. C# - 프로세스의 모든 핸들을 열람 - 세 번째 이야기
12194정성태3/16/202020977오류 유형: 607. PostgreSQL - Npgsql.NpgsqlException: sorry, too many clients already
12193정성태3/16/202017872개발 환경 구성: 485. docker - SAP Adaptive Server Enterprise 컨테이너 실행 [1]
12192정성태3/14/202019879개발 환경 구성: 484. docker - Sybase Anywhere 16 컨테이너 실행
12191정성태3/14/202021019개발 환경 구성: 483. docker - OracleXE 컨테이너 실행 [1]
12190정성태3/14/202015567오류 유형: 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/202021172개발 환경 구성: 482. Facebook OAuth 처리 시 상태 정보 전달 방법과 "유효한 OAuth 리디렉션 URI" 설정 규칙
12188정성태3/13/202025995Windows: 169. 부팅 시점에 실행되는 chkdsk 결과를 확인하는 방법
12187정성태3/12/202015523오류 유형: 605. NtpClient was unable to set a manual peer to use as a time source because of duplicate error on '...'.
12186정성태3/12/202017381오류 유형: 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/202017958오류 유형: 603. The browser service was unable to retrieve a list of servers from the browser master...
12184정성태3/11/202019887오류 유형: 602. Automatic certificate enrollment for local system failed (0x800706ba) The RPC server is unavailable. [3]
12183정성태3/11/202017688오류 유형: 601. Warning: DsGetDcName returned information for \\[...], when we were trying to reach [...].
... 61  62  63  64  65  66  67  68  [69]  70  71  72  73  74  75  ...