Skip to content
Related Articles
Get the best out of our app
GFG App
Open App
geeksforgeeks
Browser
Continue

Related Articles

C# | Creating a synchronized (thread-safe) wrapper for the ArrayList

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Synchronized(ArrayList) method is used to get an ArrayList wrapper that is synchronized (thread safe).

Syntax:

public static System.Collections.ArrayList Synchronized (System.Collections.ArrayList list);

Here, the list is the ArrayList which is to be synchronized.

Return Value: It returns an ArrayList wrapper which is synchronized (thread safe).

Exception: This method throws ArgumentNullException if the list is null.

Below programs illustrate the use of above-discussed method:

Example 1:




// C# code to check if ArrayList
// Is Synchronized or not
using System;
using System.Collections;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating an ArrayList
        ArrayList myList = new ArrayList();
  
        // Adding elements to ArrayList
        myList.Add("Geeks");
        myList.Add("for");
        myList.Add("Geeks");
        myList.Add("Noida");
        myList.Add("Geeks Classes");
        myList.Add("Delhi");
  
        // Creates a synchronized
        // wrapper around the ArrayList
        ArrayList smyList = ArrayList.Synchronized(myList);
  
        // Displays the synchronization
        // status of both ArrayList
        Console.WriteLine("myList is {0}.", myList.IsSynchronized ? 
                              "Synchronized" : "Not Synchronized");
  
        Console.WriteLine("smyList is {0}.", smyList.IsSynchronized ?
                                "Synchronized" : "Not Synchronized");
    }
}


Output:

myList is Not Synchronized.
smyList is Synchronized.

Example 2:




// C# code to check if ArrayList
// Is Synchronized or not
using System;
using System.Collections;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating an ArrayList
        ArrayList myList = new ArrayList();
  
        // Adding elements to ArrayList
        myList.Add("Geeks");
        myList.Add("for");
        myList.Add("Geeks");
        myList.Add("Noida");
        myList.Add("Geeks Classes");
        myList.Add("Delhi");
  
        // it will give error as
        // the parameter is null
        ArrayList smyList = ArrayList.Synchronized(null);
    }
}


Runtime Error:

Unhandled Exception:
System.ArgumentNullException: Value cannot be null.
Parameter name: list

Note: For the thread safety of the ArrayList, all operations must be done through this wrapper.

Reference:


My Personal Notes arrow_drop_up
Last Updated : 01 Feb, 2019
Like Article
Save Article
Similar Reads