Collections and Synchronization (Thread Safety)

By default, Collections classes are generally 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.

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), on the SyncRoot property when accessing the collection.

Only the Hashtable class guarantees thread safety, by default, when one writer and multiple readers simultaneously access the collection. It can be made thread-safe for multiple writers by using any of the methods above.

Array 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.

When implementing the Synchronized method, derived classes must remember to override the IsReadOnly property to return the correct value.

See Also

Creating and Manipulating Collections | System.Collections Namespace | System.Collections.Specialized Namespace