如何在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
热门推荐
10 圣诞祝福语简短小学
11 祖国七十华诞简短祝福语
12 老师送的祝福语简短
13 生日祝福语大全女生简短
14 祝女性生日祝福语简短
15 牛年女神节祝福语简短
16 情人表白祝福语简短大气
17 老公开业祝福语简短
18 官宣新年祝福语简短