Collection and synchronization (thread safety)
. NET Framework 2.0
- Silverlight
- . NET Framework 3.5
HTTPS://MSDN.MICROSOFT.COM/ZH-CN/LIBRARY/573THS2X (v=vs.80). aspx
By default, classes in System.Collections and related namespaces are not thread-safe. Multiple readers can safely read the collection, but any modification to the collection produces indeterminate results for all threads that access the collection, including the reader thread.
Use any of the following methods to make the System.Collections class thread-safe:
Use the Synchronized method to create a thread-safe wrapper and access the collection exclusively through the wrapper.
If the class does not have a Synchronized method, it derives from the class and implements the Synchronized method using the SyncRoot property.
Use a locking mechanism for the SyncRoot property when accessing the collection, such as the lock statement in C # ( SyncLockin Visual Basic, the Monitor class in C + +).
When implementing the Synchronized method, the derived class must override the IsReadOnly property to return the correct value.
The Array class does not contain the Synchronized method, and although it has a SyncRoot property, the class cannot derive from it. Therefore, the array is thread-safe only through the locking mechanism.
Generic collection classes do not contain synchronous members, however, some generic classes, such as Collection, Dictionary, and List, explicitly implement synchronous members that inherit from a non-generic ICollection interface.
Collection and synchronization (thread safety)