Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ตรวจสอบว่า ArrayList ถูกซิงโครไนซ์ (Thread-Safe) หรือไม่ใน C#

ภาพรวม

คุณสมบัติ ArrayList.IsSynchronized บอกว่า ArrayList เป็น synchronized wrapper (thread-safe) หรือไม่ ArrayList ธรรมดาคืนค่า false wrapper จาก ArrayList.Synchronized() คืนค่า true

ตัวอย่างที่ 1: ArrayList ธรรมดาสองตัว (ไม่ synchronized)

using System;
using System.Collections;

public class Demo
{
    public static void Main(String[] args)
    {
        ArrayList list1 = new ArrayList();
        list1.Add("A");
        list1.Add("B");
        list1.Add("C");
        list1.Add("D");
        list1.Add("E");
        list1.Add("F");
        list1.Add("G");
        list1.Add("H");
        list1.Add("I");
        Console.WriteLine("Elements in ArrayList1...");
        foreach (string res in list1)
        {
            Console.WriteLine(res);
        }
        ArrayList list2 = new ArrayList();
        list2.Add("A");
        list2.Add("B");
        list2.Add("C");
        list2.Add("D");
        list2.Add("E");
        list2.Add("F");
        list2.Add("G");
        list2.Add("H");
        list2.Add("I");
        Console.WriteLine("Elements in ArrayList2...");
        foreach (string res in list2)
        {
            Console.WriteLine(res);
        }
        Console.WriteLine("Is ArrayList synchronized? = " + list2.IsSynchronized);
    }
}

ผลลัพธ์

Elements in ArrayList1...
A
B
C
D
E
F
G
H
I
Elements in ArrayList2...
A
B
C
D
E
F
G
H
I
Is ArrayList synchronized? = False

ตัวอย่างที่ 2: สร้าง Synchronized Wrapper

using System;
using System.Collections;

public class Demo
{
    public static void Main(String[] args)
    {
        ArrayList list1 = new ArrayList();
        list1.Add("One");
        list1.Add("Two");
        list1.Add("Three");
        list1.Add("Four");
        list1.Add("Five");
        Console.WriteLine("Elements in ArrayList...");
        foreach (string res in list1)
        {
            Console.WriteLine(res);
        }
        ArrayList list = ArrayList.Synchronized(list1);
        Console.WriteLine("Is ArrayList synchronized? = " + list.IsSynchronized);
    }
}

ผลลัพธ์

Elements in ArrayList...
One
Two
Three
Four
Five
Is ArrayList synchronized? = True

คำอธิบายเพิ่มเติม

  • IsSynchronized = true หมายถึง wrapper ล็อกทุก operation สาธารณะ
  • ข้อสำคัญ: การ enumerate (foreach) **ไม่ได้** thread-safe แม้ IsSynchronized = true ต้องล็อกด้วย SyncRoot
  • Pattern มาตรฐาน: lock(list.SyncRoot) { foreach(var item in list) ... }
  • ArrayList เป็น non-generic legacy ใช้ ConcurrentBag<T>, ConcurrentQueue<T>, หรือ List<T> + lock แทน
  • Equals() เปรียบเทียบอ้างอิง ไม่ใช่เนื้อหา