Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C#에서 Hashtable에 대한 동기화된 래퍼(Synchronized Wrapper) 만들기

C#에서 Hashtable의 동기화된 래퍼(synchronized wrapper)를 만들려면 정적 메서드인 Hashtable.Synchronized()를 사용합니다. 이 메서드는 원본 Hashtable을 감싸는 스레드로부터 안전한(thread-safe) 래퍼 객체를 반환하며, 해당 객체의 IsSynchronized 속성은 true를 반환합니다.

일반적인 방식으로 생성한 Hashtable은 기본적으로 동기화되어 있지 않기 때문에 IsSynchronized 속성 값이 false입니다. 따라서 멀티스레드 환경에서 여러 스레드가 동시에 같은 Hashtable에 접근해야 한다면 반드시 동기화된 래퍼를 사용해야 데이터 무결성을 지킬 수 있습니다.

예제 1: 일반 Hashtable의 동기화 상태 확인

먼저 일반 Hashtable을 생성하고 요소를 추가한 뒤, IsSynchronized 속성으로 동기화 여부를 확인해 보겠습니다.

using System;
using System.Collections;

public class Demo {
    public static void Main() {
        Hashtable hash = new Hashtable();
        hash.Add("1", "AB");
        hash.Add("2", "CD");
        hash.Add("3", "EF");
        hash.Add("4", "GH");
        hash.Add("5", "IJ");
        hash.Add("6", "KL");

        Console.WriteLine("Hashtable elements...");
        foreach(DictionaryEntry d in hash) {
            Console.WriteLine("Key = "+d.Key + ", Value = " + d.Value);
        }
        Console.WriteLine("Hashtable is synchronized? = "+hash.IsSynchronized);
    }
}

출력 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

Hashtable elements...
Key = 1, Value = AB
Key = 2, Value = CD
Key = 3, Value = EF
Key = 4, Value = GH
Key = 5, Value = IJ
Key = 6, Value = KL
Hashtable is synchronized? = False

결과에서 알 수 있듯이 일반 Hashtable은 동기화되어 있지 않으므로 False가 출력됩니다.

예제 2: Synchronized() 메서드로 동기화된 래퍼 만들기

이번에는 Hashtable.Synchronized() 메서드를 호출하여 동기화된 래퍼를 생성하고, 원본 Hashtable과 래퍼의 동기화 여부를 비교해 보겠습니다.

using System;
using System.Collections;

public class Demo {
    public static void Main() {
        Hashtable hash = new Hashtable();
        hash.Add("1", "Mark");
        hash.Add("2", "Gary");
        hash.Add("3", "Jacob");
        hash.Add("4", "Andy");
        hash.Add("5", "Jack");

        Console.WriteLine("Hashtable elements...");
        foreach(DictionaryEntry d in hash) {
            Console.WriteLine("Key = "+d.Key + ", Value = " + d.Value);
        }
        Console.WriteLine("Hashtable is synchronized? = "+hash.IsSynchronized);

        Hashtable hash2 = Hashtable.Synchronized(hash);
        Console.WriteLine("Hashtable is synchronized? = "+hash2.IsSynchronized);
    }
}

출력 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

Hashtable elements...
Key = 1, Value = Mark
Key = 2, Value = Gary
Key = 3, Value = Jacob
Key = 4, Value = Andy
Key = 5, Value = Jack
Hashtable is synchronized? = False
Hashtable is synchronized? = True

원본 Hashtable인 hash는 동기화되어 있지 않아 False가 출력되지만, Synchronized() 메서드로 생성한 래퍼 hash2True가 출력됩니다. 이처럼 동기화된 래퍼를 사용하면 여러 스레드가 동시에 Hashtable에 접근하더라도 내부적으로 잠금이 자동으로 처리되므로 스레드 안전성을 확보할 수 있습니다.