|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here. ArchiveDisclaimer|
Collections and Synchronization (Thread Safety)
By default, classes in System.Collections and 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, the Monitor class 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.
The Array class 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 Collection<T>, Dictionary<TKey, TValue>, and List<T>, explicitly implement synchronization members inherited from the nongeneric ICollection interface.