StringCollection ক্লাস থ্রেড-সেফ নয়। মাল্টি-থ্রেডেড পরিস্থিতিতে সেফলি ব্যবহার করার জন্য lock(strCol.SyncRoot) ব্যবহার করতে হয়।
উদাহরণ ১: অ্যারে থেকে AddRange ও সিঙ্ক্রোনাইজড ইটারেশন
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("Array elements...");
foreach (string res in arr) {
Console.WriteLine(res);
}
stringCol.AddRange(arr);
Console.WriteLine("Total number of elements = " + stringCol.Count);
stringCol.RemoveAt(3);
Console.WriteLine("Total number of elements now = " + stringCol.Count);
Console.WriteLine("Synchronize access...");
lock(stringCol.SyncRoot) {
foreach(object ob in stringCol) {
Console.WriteLine(ob);
}
}
}
}
আউটপুট
Array elements... 100 200 300 400 500 Total number of elements = 5 Total number of elements now = 4 Synchronize access... 100 200 300 500
উদাহরণ ২: সরাসরি স্ট্রিং যোগ করে সিঙ্ক্রোনাইজ করা
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("Synchronize access...");
lock(strCol.SyncRoot) {
foreach(object ob in strCol) {
Console.WriteLine(ob);
}
}
}
}
আউটপুট
Synchronize access... Katie Philips Jacob Carl Gary
সারসংক্ষেপ
SyncRootপ্রপার্টি লকে অবজেক্ট প্রদান করে।lock(strCol.SyncRoot)ব্লকের ভিতরে ইটারেশন বা মডিফিকেশন করুন।IsSynchronizedপ্রপার্টি সবসময়falseরিটার্ন করে।