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

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

Ví dụ 1

Sử dụng lock trên SyncRoot của ListDictionary:

using System;
using System.Collections;
using System.Collections.Specialized;

public class Demo {
    public static void Main() {
        ListDictionary dict = new ListDictionary();
        dict.Add("1", "SUV");
        dict.Add("2", "Sedan");
        dict.Add("3", "Utility Vehicle");
        dict.Add("4", "Compact Car");
        dict.Add("5", "SUV");
        dict.Add("6", "Sedan");
        dict.Add("7", "Utility Vehicle");
        dict.Add("8", "Compact Car");
        dict.Add("9", "Crossover");
        dict.Add("10", "Electric Car");
        
        Console.WriteLine("Các phần tử ListDictionary...");
        foreach(DictionaryEntry d in dict) {
            Console.WriteLine(d.Key + " " + d.Value);
        }
        
        Console.WriteLine("\nKích thước cố định? = " + dict.IsFixedSize);
        Console.WriteLine("Chỉ đọc? = " + dict.IsReadOnly);
        Console.WriteLine("Đồng bộ? = " + dict.IsSynchronized);
        Console.WriteLine("Có khóa K? = " + dict.Contains("K"));
        Console.WriteLine("Có khóa 9? = " + dict.Contains("9"));
        
        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ử ListDictionary...
1 SUV
2 Sedan
3 Utility Vehicle
4 Compact Car
5 SUV
6 Sedan
7 Utility Vehicle
8 Compact Car
9 Crossover
10 Electric Car
Kích thước cố định? = False
Chỉ đọc? = False
Đồng bộ? = False
Có khóa K? = False
Có khóa 9? = True
Truy cập đồng bộ...
1 SUV
2 Sedan
3 Utility Vehicle
4 Compact Car
5 SUV
6 Sedan
7 Utility Vehicle
8 Compact Car
9 Crossover
10 Electric Car

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() {
        ListDictionary dict = new ListDictionary();
        dict.Add("A", "Books");
        dict.Add("B", "Electronics");
        dict.Add("C", "Appliances");
        dict.Add("D", "Pet Supplies");
        dict.Add("E", "Clothing");
        dict.Add("F", "Footwear");
        
        Console.WriteLine("Truy cập đồng bộ...");
        lock(dict.SyncRoot) {
            foreach(DictionaryEntry d in dict) {
                Console.WriteLine(d.Key + " " + d.Value);
            }
        }
    }
}

Kết quả

Truy cập đồng bộ...
A Books
B Electronics
C Appliances
D Pet Supplies
E Clothing
F Footwear