Ví dụ 1
Sử dụng lock trên SyncRoot của StringCollection:
using System;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
StringCollection stringCol = new StringCollection();
String[] arr = new String[] { "100", "200", "300", "400", "500" };
Console.WriteLine("Các phần tử mảng...");
foreach (string res in arr) {
Console.WriteLine(res);
}
stringCol.AddRange(arr);
Console.WriteLine("Tổng số phần tử = " + stringCol.Count);
stringCol.RemoveAt(3);
Console.WriteLine("Tổng số phần tử hiện tại = " + stringCol.Count);
Console.WriteLine("Truy cập đồng bộ...");
lock(stringCol.SyncRoot) {
foreach(object ob in stringCol) {
Console.WriteLine(ob);
}
}
}
}
Kết quả
Các phần tử mảng...
100
200
300
400
500
Tổng số phần tử = 5
Tổng số phần tử hiện tại = 4
Truy cập đồng bộ...
100
200
300
500
Ví dụ 2
using System;
using System.Collections.Specialized;
public class Demo {
public static void Main() {
StringCollection strCol = new StringCollection();
strCol.Add("Katie");
strCol.Add("Philips");
strCol.Add("Jacob");
strCol.Add("Carl");
strCol.Add("Gary");
Console.WriteLine("Truy cập đồng bộ...");
lock(strCol.SyncRoot) {
foreach(object ob in strCol) {
Console.WriteLine(ob);
}
}
}
}
Kết quả
Truy cập đồng bộ...
Katie
Philips
Jacob
Carl
Gary