ListDictionary.SyncRoot Property is used to get an object which can be used to synchronize access to the ListDictionary. ListDictionary is a specialized collection. It comes under the System.Collections.Specialized namespace. This type represents a non-generic dictionary type. It is implemented with a linked list.
Syntax: public virtual object SyncRoot { get; }
Property Value: An object which can be used to synchronize access to the ListDictionary.
Important Points:
- Synchronization of an object is done so that only one thread can manipulate the data in the ListDictionary.
- 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 ListDictionary named listdict, which is not a thread-safe procedure and can cause an exception. So to avoid the exception we lock the collection during the enumeration.
using System;
using System.Threading;
using System.Collections;
using System.Collections.Specialized;
namespace sync_root {
class GFG {
static void Main( string [] args)
{
ListDictionary listdict = new ListDictionary();
listdict.Add( "10" , "JQUERY" );
listdict.Add( "20" , "HTML" );
listdict.Add( "30" , "CSS" );
listdict.Add( "40" , "C" );
listdict.Add( "50" , "C++" );
listdict.Add( "60" , "C#" );
lock (listdict.SyncRoot)
{
foreach (DictionaryEntry i in listdict)
Console.WriteLine(i.Key + " ---- " + i.Value);
}
}
}
}
|
Output:
10 ---- JQUERY
20 ---- HTML
30 ---- CSS
40 ---- C
50 ---- C++
60 ---- C#
Example 2:
using System;
using System.Threading;
using System.Collections;
using System.Collections.Specialized;
namespace sync_root {
class GFG {
static void Main( string [] args)
{
ListDictionary listdict = new ListDictionary();
listdict.Add( "1" , "Ram" );
listdict.Add( "2" , "Shyam" );
listdict.Add( "3" , "Mohan" );
listdict.Add( "4" , "Sohan" );
listdict.Add( "5" , "Rohan" );
lock (listdict.SyncRoot)
{
foreach (DictionaryEntry i in listdict)
Console.WriteLine(i.Key + " ----> " + i.Value);
}
}
}
}
|
Output:
1 ----> Ram
2 ----> Shyam
3 ----> Mohan
4 ----> Sohan
5 ----> Rohan
Reference:
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!