SortedList क्लास थ्रेड-सेफ नहीं है। मल्टी-थ्रेड वातावरण में थ्रेड सुरक्षा के लिए SortedList.Synchronized() स्टैटिक मेथड का उपयोग करके सिंक्रोनाइज़्ड रैपर बनाया जा सकता है।
उदाहरण 1: सिंक्रोनाइज़्ड रैपर बनाना और जांचना
using System;
using System.Collections;
public class Demo {
public static void Main() {
SortedList sortedList = new SortedList();
sortedList.Add("1", "Tom");
sortedList.Add("2", "Ryan");
sortedList.Add("3", "Nathan");
Console.WriteLine("SortedList तत्व...");
foreach (DictionaryEntry entry in sortedList) {
Console.WriteLine("Key = " + entry.Key + ", Value = " + entry.Value);
}
// सिंक्रोनाइज़्ड रैपर बनाएं
SortedList syncList = SortedList.Synchronized(sortedList);
Console.WriteLine("\nक्या SortedList सिंक्रोनाइज़्ड है? = " + syncList.IsSynchronized);
}
}
आउटपुट
SortedList तत्व...
Key = 1, Value = Tom
Key = 2, Value = Ryan
Key = 3, Value = Nathan
क्या SortedList सिंक्रोनाइज़्ड है? = True
उदाहरण 2: बिना रैपर के SortedList (डिफ़ॉल्ट असिंक्रोनाइज़्ड)
using System;
using System.Collections;
public class Demo {
public static void Main() {
SortedList sortedList = new SortedList();
sortedList.Add("1", "AB");
sortedList.Add("2", "CD");
sortedList.Add("3", "EF");
sortedList.Add("4", "GH");
sortedList.Add("5", "IJ");
sortedList.Add("6", "KL");
Console.WriteLine("SortedList तत्व...");
foreach (DictionaryEntry entry in sortedList) {
Console.WriteLine("Key = " + entry.Key + ", Value = " + entry.Value);
}
// मूल SortedList की IsSynchronized प्रॉपर्टी जांचें
Console.WriteLine("\nक्या मूल SortedList सिंक्रोनाइज़्ड है? = " + sortedList.IsSynchronized);
}
}
आउटपुट
SortedList तत्व...
Key = 1, Value = AB
Key = 2, Value = CD
Key = 3, Value = EF
Key = 4, Value = GH
Key = 5, Value = IJ
Key = 6, Value = KL
क्या मूल SortedList सिंक्रोनाइज़्ड है? = False
महत्वपूर्ण बिंदु
SortedList.Synchronized()एक थ्रेड-सेफ रैपर लौटाता है।- मूल
SortedListकीIsSynchronizedप्रॉपर्टीfalseहोती है। - रैपर की
IsSynchronizedप्रॉपर्टीtrueहोती है। - सिंक्रोनाइज़्ड रैपर पर सभी ऑपरेशन थ्रेड-सेफ होते हैं।
- एन्यूमरेशन के दौरान मैन्युअल लॉकिंग अभी भी आवश्यक हो सकती है।