Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Lấy quyền truy cập đồng bộ cho StringDictionary trong C#

Ví dụ 1

Sử dụng lock trên SyncRoot:

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("Các cặp khóa-giá trị StringDictionary...");
        foreach(DictionaryEntry de in strDict) {
            Console.WriteLine(de.Key + " " + de.Value);
        }
        
        Console.WriteLine("Giá trị khóa D = " + strDict["D"]);
        Console.WriteLine("Giá trị khóa F = " + strDict["F"]);
        
        Console.WriteLine("\nTruy cập đồng bộ..");
        lock(strDict.SyncRoot) {
            foreach(DictionaryEntry de in strDict) {
                Console.WriteLine(de.Key + " " + de.Value);
            }
        }
    }
}

Kết quả

Các cặp khóa-giá trị StringDictionary...
a Books
b Electronics
c Appliances
d Pet Supplies
e Clothing
f Footwear
Giá trị khóa D = Pet Supplies
Giá trị khóa F = Footwear
Truy cập đồng bộ..
a Books
b Electronics
c Appliances
d Pet Supplies
e Clothing
f Footwear

Ví dụ 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("Các phần tử StringDictionary...");
        foreach(DictionaryEntry de in strDict) {
            Console.WriteLine(de.Key + " " + de.Value);
        }
        
        Console.WriteLine("\nTruy cập đồng bộ..");
        lock(strDict.SyncRoot) {
            foreach(DictionaryEntry de in strDict) {
                Console.WriteLine(de.Key + " " + de.Value);
            }
        }
    }
}

Kết quả

Các phần tử StringDictionary...
a John
b Andy
c Tim
d Ryan
e Kevin
f Katie
g Brad
Truy cập đồng bộ..
a John
b Andy
c Tim
d Ryan
e Kevin
f Katie
g Brad