How to get Synchronize access to the StringCollection in C#

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:

Synchronization of an object is done so that only one thread can manipulate the data in the StringCollection.

A property is a member of a class that provides a means for reading, writing and computing private data fields.

The synchronizing code cannot directly perform on the collection, so it must perform operations on the SyncRoot of the collection in order to guarantee the proper operation of collections that are derived from other objects.

Retrieving the value of this property is an O(1) operation.

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.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.