Giới thiệu
Mảng trong C# implement ICollection, có thuộc tính IsSynchronized chỉ ra liệu truy cập mảng có an toàn luồng (thread-safe) hay không. Mảng thường không đồng bộ hóa (false).
Ví dụ 1: Kiểm tra mảng rỗng
using System;
public class Demo
{
public static void Main()
{
string[] products = new string[] { };
Console.WriteLine("One or more planets begin with 'E'? = {0}",
Array.Exists(products, ele => ele.StartsWith("E")));
Console.WriteLine("Is the array having fixed size? = " + products.IsFixedSize);
Console.WriteLine("Is the array read only? = " + products.IsReadOnly);
Console.WriteLine("Is the array synchronized? = " + products.IsSynchronized);
}
}
Kết quả
One or more planets begin with 'E'? = False Is the array having fixed size? = True Is the array read only? = False Is the array synchronized? = False
Ví dụ 2: So sánh hai mảng chuỗi
using System;
public class Demo
{
public static void Main()
{
String[] strArr1 = new String[3] { "John", "Jacob", "Tim" };
String[] strArr2 = new String[3] { "Tom", "Brad", "Bradley" };
Console.WriteLine("First String array...");
foreach (string val in strArr1)
{
Console.WriteLine(val);
}
Console.WriteLine("Is the 1st array having fixed size? = " + strArr1.IsFixedSize);
Console.WriteLine("Is the 1st array read only? = " + strArr1.IsReadOnly);
Console.WriteLine("Is the 1st array synchronized? = " + strArr1.IsSynchronized);
Console.WriteLine("\nSecond String array...");
foreach (string val in strArr2)
{
Console.WriteLine(val);
}
Console.WriteLine("Is the 2nd array having fixed size? = " + strArr2.IsFixedSize);
Console.WriteLine("Is the 2nd array read only? = " + strArr2.IsReadOnly);
Console.WriteLine("Is the 2nd array synchronized? = " + strArr2.IsSynchronized);
Console.WriteLine("Are both the array objects equal? = " + strArr1.Equals(strArr2));
}
}
Kết quả
First String array... John Jacob Tim Is the 1st array having fixed size? = True Is the 1st array read only? = False Is the 1st array synchronized? = False Second String array... Tom Brad Bradley Is the 2nd array having fixed size? = True Is the 2nd array read only? = False Is the 2nd array synchronized? = False Are both the array objects equal? = False
Giải thích các thuộc tính
| Thuộc tính | Giá trị mảng | Giải thích |
|---|---|---|
| IsFixedSize | true | Kích thước mảng cố định sau khi tạo |
| IsReadOnly | false | Có thể sửa đổi phần tử (gán giá trị mới) |
| IsSynchronized | false | KHÔNG an toàn luồng mặc định |
Làm sao để có mảng đồng bộ hóa?
// Array không có wrapper synchronizedbuiltin
// Cách 1: Lock thủ công
lock (array.SyncRoot) { /* truy cập */ }
// Cách 2: Dùng List<T> + lock
// Cách 3: Dùng Concurrent collections (System.Collections.Concurrent)
var concurrentBag = new ConcurrentBag<string>();
var concurrentDict = new ConcurrentDictionary<int, string>();
var blockingCollection = new BlockingCollection<string>();
Khuyến nghị
Tránh dùng mảng trong đa luồng. Sử dụng System.Collections.Concurrent hoặc ImmutableArray<T> cho an toàn luồng tốt hơn.