Collections and Synchronization (Thread Safety)
By default, classes inand related namespaces are not thread safe. Multiple readers can read the collection with confidence; however, any modification to the collection produces undefined results for all threads that access the collection, including the reader threads.
System.Collections classes can be made thread safe using any of the following methods:
Create a thread-safe wrapper using the Synchronized method, and access the collection exclusively through that wrapper.
If the class does not have a Synchronized method, derive from the class and implement a Synchronized method using the SyncRoot property.
Use a locking mechanism, such as the lock statement in C# (SyncLock in Visual Basic, theclass in C++), on the SyncRoot property when accessing the collection.
When implementing the Synchronized method, derived classes must override the IsReadOnly property to return the correct value.
Theclass does not include a Synchronized method and, although it has a SyncRoot property, the class cannot be derived from. Therefore, an array can be made thread safe only through the locking mechanism.
Generic collection classes do not include synchronization members; however, some generic classes, such as, , and , explicitly implement synchronization members inherited from the nongeneric interface.