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

Kiểm tra Hashtable có đồng bộ (synchronized) trong C#

Giới thiệu

Hashtable (namespace System.Collections) là bảng băm khóa-giá trị không generic. Mặc định IsSynchronized trả về false. Để có bản sao thread-safe, dùng Hashtable.Synchronized(hashtable).

Ví dụ 1: Tạo Hashtable đồng bộ

using System;
using System.Collections;

public class Demo
{
    public static void Main()
    {
        Hashtable hash = new Hashtable();
        hash.Add("One", "Katie");
        hash.Add("Two", "John");
        hash.Add("Three", "Barry");
        hash.Add("Four", "");
        hash.Add("Five", "Harry");
        hash.Add("Six", "F");
        hash.Add("Seven", "Tom");
        hash.Add("Eight", "Andy");
        hash.Add("Nine", "I");
        hash.Add("Ten", "Tim");

        Console.WriteLine("Các cặp khóa-giá trị Hashtable...");
        foreach (DictionaryEntry entry in hash)
        {
            Console.WriteLine("{0} and {1} ", entry.Key, entry.Value);
        }

        Console.WriteLine("Hashtable có kích thước cố định? = " + hash.IsFixedSize);
        Console.WriteLine("Hashtable chỉ đọc? = " + hash.IsReadOnly);

        Hashtable hash2 = Hashtable.Synchronized(hash);
        Console.WriteLine("Hash đã đồng bộ? = " + hash2.IsSynchronized);
    }
}

Kết quả

Các cặp khóa-giá trị Hashtable...
One and Katie
Ten and Tim
Five and Harry
Three and Barry
Seven and Tom
Two and John
Four and 
Eight and Andy
Nine and I
Six and F
Hashtable có kích thước cố định? = False
Hashtable chỉ đọc? = False
Hash đã đồng bộ? = True

Ví dụ 2: Hashtable không đồng bộ

using System;
using System.Collections;

public class Demo
{
    public static void Main()
    {
        Hashtable hash = new Hashtable();
        hash.Add("One", 1);
        hash.Add("Two", 2);
        hash.Add("Three", 2);
        hash.Add("Four", 4);
        hash.Add("Five", 5);
        hash.Add("Six", 6);
        hash.Add("Seven", 7);

        Console.WriteLine("Các cặp khóa-giá trị Hashtable...");
        foreach (DictionaryEntry entry in hash)
        {
            Console.WriteLine("{0} and {1} ", entry.Key, entry.Value);
        }

        Console.WriteLine("Hashtable có kích thước cố định? = " + hash.IsFixedSize);
        Console.WriteLine("Hashtable chỉ đọc? = " + hash.IsReadOnly);
        Console.WriteLine("Hash đã đồng bộ? = " + hash.IsSynchronized);
    }
}

Kết quả

Các cặp khóa-giá trị Hashtable...
One and 1
Five and 5
Three and 2
Seven and 7
Two and 2
Four and 4
Six and 6
Hashtable có kích thước cố định? = False
Hashtable chỉ đọc? = False
Hash đã đồng bộ? = False

Lưu ý

  • Hashtable.Synchronized trả về wrapper thread-safe cho các thao tác đơn lẻ.
  • Khi duyệt (enumerate) trên Hashtable đồng bộ, vẫn cần khóa (lock) thủ công trên SyncRoot.
  • Trong code mới, ưu tiên ConcurrentDictionary<TKey, TValue> (namespace System.Collections.Concurrent) cho đa luồng.