Collections and Synchronization (Thread Safety)

[This documentation is for preview only, and is subject to change in later releases. Blank topics are included as placeholders.]

The .NET Framework version 4 Beta 1 introduces a new set of thread-safe collection classes in the System.Collections.Concurrent namespace. You should use these new collection classes whenever possible, because they handle thread synchronization issues automatically and efficiently, and thereby greatly reduce potential errors in your program. The new concurrent collections include ConcurrentLinkedList<T>, ConcurrentDictionary<TKey, TValue>, ConcurrentQueue<T>, ConcurrentStack<T>, and others.

Note Note

The following text applies only to programs that must target versions of the .NET Framework before version 4.

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.