Ví dụ 1
Sử dụng lock trên SyncRoot để đồng bộ HybridDictionary:
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
HybridDictionary dict1 = new HybridDictionary();
dict1.Add("A", "Books");
dict1.Add("B", "Electronics");
dict1.Add("C", "Smart Wearables");
dict1.Add("D", "Pet Supplies");
dict1.Add("E", "Clothing");
dict1.Add("F", "Footwear");
Console.WriteLine("Các phần tử HybridDictionary1...");
foreach(DictionaryEntry d in dict1) {
Console.WriteLine(d.Key + " " + d.Value);
}
Console.WriteLine("Kích thước cố định? = " + dict1.IsFixedSize);
Console.WriteLine("Chỉ đọc? = " + dict1.IsReadOnly);
Console.WriteLine("Đồng bộ? = " + dict1.IsSynchronized);
HybridDictionary dict2 = new HybridDictionary();
dict2.Add("1", "One");
dict2.Add("2", "Two");
dict2.Add("3", "Three");
dict2.Add("4", "Four");
dict2.Add("5", "Five");
dict2.Add("6", "Six");
Console.WriteLine("\nCác phần tử HybridDictionary2...");
foreach(DictionaryEntry d in dict2) {
Console.WriteLine(d.Key + " " + d.Value);
}
Console.WriteLine("Dict1 bằng Dict2? = " + (dict1.Equals(dict2)));
Console.WriteLine("\nTruy cập đồng bộ...");
lock(dict2.SyncRoot) {
foreach(DictionaryEntry d in dict2) {
Console.WriteLine(d.Key + " " + d.Value);
}
}
}
}
Kết quả
Các phần tử HybridDictionary1...
A Books
B Electronics
C Smart Wearables
D Pet Supplies
E Clothing
F Footwear
Kích thước cố định? = False
Chỉ đọc? = False
Đồng bộ? = False
Các phần tử HybridDictionary2...
1 One
2 Two
3 Three
4 Four
5 Five
Six
Dict1 bằng Dict2? = False
Truy cập đồng bộ...
1 One
2 Two
3 Three
4 Four
5 Five
6 Six
Ví dụ 2
Ví dụ đơn giản hơn:
using System;
using System.Collections;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
HybridDictionary dict = new HybridDictionary();
dict.Add("A", "SUV");
dict.Add("B", "MUV");
dict.Add("C", "AUV");
Console.WriteLine("Các phần tử HybridDictionary...");
foreach(DictionaryEntry d in dict) {
Console.WriteLine(d.Key + " " + d.Value);
}
Console.WriteLine("\nTruy cập đồng bộ...");
lock(dict.SyncRoot) {
foreach(DictionaryEntry d in dict) {
Console.WriteLine(d.Key + " " + d.Value);
}
}
}
}
Kết quả
Các phần tử HybridDictionary...
A SUV
B MUV
C AUV
Truy cập đồng bộ...
A SUV
B MUV
C AUV