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

C#에서 StringDictionary에 대한 동기화된 액세스를 얻는 방법

StringDictionary는 키와 값이 모두 문자열로 제한되는 해시 테이블 기반 컬렉션입니다. 멀티스레드 환경에서 여러 스레드가 동시에 컬렉션에 접근하면 데이터 불일치나 예외가 발생할 수 있습니다. 이를 방지하려면 SyncRoot 속성을 활용해 컬렉션 자체에 대한 잠금을 걸어야 합니다.

StringDictionary에 대해 동기화된 액세스를 얻으려면 lock 블록 안에서 SyncRoot 속성을 사용하면 됩니다. 아래 예제를 통해 살펴보겠습니다.

예제 1

using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
   public static void Main(){
      StringDictionary strDict = new StringDictionary ();
      strDict.Add("A", "Books");
      strDict.Add("B", "Electronics");
      strDict.Add("C", "Appliances");
      strDict.Add("D", "Pet Supplies");
      strDict.Add("E", "Clothing");
      strDict.Add("F", "Footwear");
      Console.WriteLine("StringDictionary key-value pairs...");
      foreach(DictionaryEntry de in strDict) {
         Console.WriteLine(de.Key + " " + de.Value);
      }
      Console.WriteLine("Value associated with key D = "+strDict["D"]);
      Console.WriteLine("Value associated with key F = "+strDict["F"]);
      Console.WriteLine("\nSynchronize access..");
      lock(strDict.SyncRoot) {
         foreach(DictionaryEntry de in strDict) {
            Console.WriteLine(de.Key + " " + de.Value);
         }
      }
   }
}

출력 결과

위 코드를 실행하면 다음과 같은 출력이 생성됩니다 −

StringDictionary key-value pairs...
a Books
b Electronics
c Appliances
d Pet Supplies
e Clothing
f Footwear
Value associated with key D = Pet Supplies
Value associated with key F = Footwear
Synchronize access..
a Books
b Electronics
c Appliances
d Pet Supplies
e Clothing
f Footwear

출력 결과에서 알 수 있듯이, StringDictionary는 키를 소문자로 변환하여 저장합니다. 또한 인덱서(strDict["D"])를 통해 특정 키에 연결된 값을 간단히 조회할 수 있습니다. 마지막으로 lock(strDict.SyncRoot) 블록 내부에서 컬렉션을 순회함으로써 다른 스레드가 동시에 접근하지 못하도록 동기화 처리를 수행했습니다.

예제 2

이번에는 다른 예제를 살펴보겠습니다 −

using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
   public static void Main() {
      StringDictionary strDict = new StringDictionary();
      strDict.Add("A", "John");
      strDict.Add("B", "Andy");
      strDict.Add("C", "Tim");
      strDict.Add("D", "Ryan");
      strDict.Add("E", "Kevin");
      strDict.Add("F", "Katie");
      strDict.Add("G", "Brad");
      Console.WriteLine("StringDictionary elements...");
      foreach(DictionaryEntry de in strDict) {
         Console.WriteLine(de.Key + " " + de.Value);
      }
      Console.WriteLine("\nSynchronize access..");
      lock(strDict.SyncRoot) {
         foreach(DictionaryEntry de in strDict) {
            Console.WriteLine(de.Key + " " + de.Value);
         }
      }
   }
}

출력 결과

위 코드를 실행하면 다음과 같은 출력이 생성됩니다 −

StringDictionary elements...
a John
b Andy
c Tim
d Ryan
e Kevin
f Katie
g Brad

Synchronize access..
a John
b Andy
c Tim
d Ryan
e Kevin
f Katie
g Brad

핵심 정리

  • SyncRoot 속성: 컬렉션에 대한 동기화 작업에 사용할 수 있는 객체를 반환합니다.
  • lock 문: 지정한 객체에 대한 상호 배제(mutual exclusion)를 보장하여, 한 번에 하나의 스레드만 해당 블록을 실행하도록 합니다.
  • 컬렉션 전체를 열거하는 동안에는 반드시 lock 블록 내에서 수행해야 스레드 안전성을 확보할 수 있습니다.