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

C#에서 SortedList 개체의 동기화된(Synchronized) 래퍼 만들기

C#에서 SortedList 개체에 대한 동기화된 래퍼를 만들려면 정적 메서드인 SortedList.Synchronized()를 사용하면 됩니다. 이 메서드는 원본 SortedList를 감싸는 스레드로부터 안전한(thread-safe) 래퍼를 반환하며, 여러 스레드가 동시에 컬렉션에 접근해도 안전하게 동작하도록 보장합니다.

래퍼가 실제로 동기화되었는지는 IsSynchronized 속성을 통해 확인할 수 있습니다.

예제 1: Synchronized()로 동기화된 래퍼 만들기

using System;
using System.Collections;
public class Demo {
   public static void Main(){
      SortedList sortedList = new SortedList();
      sortedList.Add("1", "Tom");
      sortedList.Add("2", "Ryan");
      sortedList.Add("3", "Nathan");
      Console.WriteLine("SortedList 요소...");
      foreach(DictionaryEntry d in sortedList){
         Console.WriteLine("Key = "+d.Key + ", Value = " + d.Value);
      }
      SortedList sortedList2 = SortedList.Synchronized(sortedList);
      Console.WriteLine("SortedList가 동기화되었습니까? = "+sortedList2.IsSynchronized);
   }
}

출력 결과

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

SortedList 요소...
Key = 1, Value = Tom
Key = 2, Value = Ryan
Key = 3, Value = Nathan
SortedList가 동기화되었습니까? = True

SortedList.Synchronized(sortedList) 호출 후 반환된 개체의 IsSynchronized 값이 True인 것을 확인할 수 있습니다. 이는 해당 래퍼가 스레드로부터 안전함을 의미합니다.

예제 2: 동기화되지 않은 일반 SortedList

이번에는 별도의 동기화 처리 없이 일반적인 SortedList를 사용하는 경우를 살펴보겠습니다.

using System;
using System.Collections;
public class Demo {
   public static void Main(){
      SortedList sortedList = new SortedList();
      sortedList.Add("1", "AB");
      sortedList.Add("2", "CD");
      sortedList.Add("3", "EF");
      sortedList.Add("4", "GH");
      sortedList.Add("5", "IJ");
      sortedList.Add("6", "KL");
      Console.WriteLine("SortedList 요소...");
      foreach(DictionaryEntry d in sortedList){
         Console.WriteLine("Key = "+d.Key + ", Value = " + d.Value);
      }
      Console.WriteLine("SortedList가 동기화되었습니까? = "+sortedList.IsSynchronized);
   }
}

출력 결과

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

SortedList 요소...
Key = 1, Value = AB
Key = 2, Value = CD
Key = 3, Value = EF
Key = 4, Value = GH
Key = 5, Value = IJ
Key = 6, Value = KL
SortedList가 동기화되었습니까? = False

Synchronized() 메서드를 사용하지 않은 일반 SortedList의 IsSynchronized 값은 False입니다. 즉, 기본 SortedList는 스레드로부터 안전하지 않으므로 멀티스레드 환경에서는 반드시 SortedList.Synchronized()로 감싼 래퍼를 사용하는 것이 좋습니다.