C# | Creating a synchronized (thread-safe) wrapper for a SortedList object
SortedList.Synchronized(SortedList) Method is used to get the synchronized (thread-safe) wrapper for a SortedList object.
Syntax:
public static System.Collections.SortedList Synchronized (System.Collections.SortedList list);
Here, list is the name of the SortedList object which is to be synchronized.
Exception: This method will throw ArgumentNullException
if the list is null.
Below programs illustrate the use of above-discussed method:
Example 1:
// C# code to create a synchronized // (thread-safe) wrapper for a // SortedList object using System; using System.Collections; class GFG { // Driver code public static void Main() { // Creating an SortedList SortedList mySortedList = new SortedList(); // Adding elements to SortedList mySortedList.Add( "1" , "one" ); mySortedList.Add( "2" , "two" ); mySortedList.Add( "3" , "three" ); mySortedList.Add( "4" , "four" ); mySortedList.Add( "5" , "five" ); // Creating a synchronized wrapper // around the SortedList. SortedList mySortedList_1 = SortedList.Synchronized(mySortedList); // --------- Using IsSynchronized Property // print the status of both SortedList Console.WriteLine( "mySortedList SortedList is {0}." , mySortedList.IsSynchronized ? "synchronized" : "not synchronized" ); Console.WriteLine( "mySortedList_1 SortedList is {0}." , mySortedList_1.IsSynchronized ? "synchronized" : "not synchronized" ); } } |
Output:
mySortedList SortedList is not synchronized. mySortedList_1 SortedList is synchronized.
Example 2:
// C# code to create a synchronized // (thread-safe) wrapper for a // SortedList object using System; using System.Collections; class GFG { // Driver code public static void Main() { // Creating an SortedList SortedList mySortedList = new SortedList(); // Adding elements in SortedList mylist.Add( "4" , "Even" ); mylist.Add( "9" , "Odd" ); mylist.Add( "5" , "Odd and Prime" ); mylist.Add( "2" , "Even and Prime" ); // it will give runtime error as // table parameter can't be null SortedList my2 = SortedList.Synchronized( null ); } } |
Runtime Error:
Unhandled Exception:
System.ArgumentNullException: Value cannot be null.
Parameter name: list
Note: For the thread safety of a SortedList object, all operations must be done through this wrapper only.
Reference:
Please Login to comment...