如何在 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("
Synchronize 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("
Synchronize 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

更新於: 11-Dec-2019

54 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始吧
廣告
© . All rights reserved.