StringCollection को थ्रेड-सेफ बनाने के लिए SyncRoot प्रॉपर्टी के साथ lock स्टेटमेंट का उपयोग करें।
उदाहरण 1: Array से StringCollection में 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
उदाहरण 2: सीधे Add के साथ
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
महत्वपूर्ण बिंदु
StringCollectionथ्रेड-सेफ नहीं है डिफ़ॉल्ट रूप सेSyncRootलॉकिंग के लिए ऑब्जेक्ट प्रदान करता हैlockकेवल एन्यूमरेशन ही नहीं, सभी एक्सेस (Add, Remove, Insert, Clear, Indexer) के लिए उपयोग करेंStringCollectionनॉन-जेनेरिक है (केवलstringस्टोर करता है)
आधुनिक विकल्प: ConcurrentBag / ConcurrentQueue / List + Lock
// थ्रेड-सेफ कलेक्शन्स (System.Collections.Concurrent)
var bag = new ConcurrentBag<string>();
bag.Add("Item1"); // थ्रेड-सेफ
var queue = new ConcurrentQueue<string>();
queue.Enqueue("Item1"); // थ्रेड-सेफ
// या List<T> + lock (अधिक कंट्रोल के लिए)
var list = new List<string>();
private readonly object _lock = new object();
lock (_lock) {
list.Add("Item1");
// अन्य ऑपरेशन्स
}
StringCollection vs आधुनिक विकल्प
| विशेषता | StringCollection + SyncRoot | ConcurrentBag/Queue | List + Lock |
|---|---|---|---|
| थ्रेड सेफ्टी | मैन्युअल | बिल्ट-इन | मैन्युअल |
| ऑर्डर प्रिजर्वेशन | हाँ | नहीं (Bag) / हाँ (Queue) | हाँ |
| इंडेक्स एक्सेस | हाँ | नहीं | हाँ |
| पेरफॉरमेंस | मीडियम | हाई (लॉक-मुक्त) | मीडियम |
सिफारिश
नए कोड के लिए Concurrent संग्रह या List<T> + समर्पित लॉक ऑब्जेक्ट का उपयोग करें। StringCollection लिगेसी है।