How to get Synchronize access to the StringCollection in C# (original) (raw)

Last Updated : 21 Feb, 2019

StringCollection.SyncRoot Property is used to get an object which can be used to synchronize access to the StringCollection. This class library that represents a collection of strings. StringCollection class is defined in the System.Collections.Specialized namespace.

Syntax: public virtual object SyncRoot { get; }Property Value: An object which can be used to synchronize access to the StringCollection.

Important Points:

Below programs illustrate the use of the above-discussed property:Example 1: In this code, we are using SyncRoot to get Synchronized access to the StringCollection named st, which is not a thread-safe procedure and can cause an exception. So to avoid the exception we lock the collection during the enumeration.

csharp `

// C# program to illustrate the // use of SyncRoot property of // the StringCollection class using System; using System.Threading; using System.Collections; using System.Collections.Specialized;

namespace sync_root {

class GFG {

// Main Method
static void Main(string[] args)
{

    // Declaring an StringCollection
    StringCollection st = new StringCollection();

    // Adding elements to StringCollection
    st.Add("C");
    st.Add("C++");
    st.Add("Java");
    st.Add("C#");
    st.Add("HTML");

    // Using the SyncRoot property
    lock(st.SyncRoot)
    {
        foreach(object ob in st)
        {
            Console.WriteLine(ob);
        }
    }
}

} }

`

Output:

C C++ Java C# HTML

Example 2:

csharp `

// C# program to illustrate the // use of SyncRoot property of // the StringCollection class using System; using System.Threading; using System.Collections; using System.Collections.Specialized;

namespace sync_root {

class GFG {

// Main Method
static void Main(string[] args)
{

    // Declaring an StringCollection
    StringCollection st = new StringCollection();

    // Adding elements to StringCollection
    st.Add("Geeks");
    st.Add("Classes");
    st.Add("on");
    st.Add("Data Structure");
    st.Add("Noida");

    // Using the SyncRoot property
    lock(st.SyncRoot)
    {
        foreach(object ob in st)
        {
            Console.WriteLine(ob);
        }
    }
}

} }

`

Output:

Geeks Classes on Data Structure Noida

Reference:

Similar Reads