Computer >> 컴퓨터 >  >> 프로그램 작성 >> C#

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

<시간/>

StringDictionary에 대한 동기화 액세스를 얻으려면 코드는 다음과 같습니다. -

예시

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

예시

다른 예를 살펴보겠습니다 -

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