Section 26.6. Synchronized Collections


26.6. Synchronized Collections

In Chapter 15, we discussed multithreading. Most of the non-generic collections are unsynchronized by default, so they can operate efficiently when multithreading is not required. Because they are unsynchronized, however, concurrent access to a collection by multiple threads could cause logic errors in your programs. To prevent potential threading problems, synchronization wrappers are provided for many of the collections that might be accessed by multiple threads. A wrapper object receives method calls, adds thread synchronization (to prevent concurrent access to the collection) and passes the calls to the wrapped collection object. Most of the non-generic collection classes in the .NET Framework provide Shared method Synchronized, which returns a synchronized wrapper object for the specified object. For example, the following code creates a synchronized ArrayList:

 Dim unsafeList As New ArrayList() Dim threadSafeList As ArrayList = ArrayList.Synchronized(unsafeList) 


The collections in the .NET Framework do not all provide wrappers for thread safety. Some do not guarantee any thread safety at all. Many of the generic collections are inherently thread-safe for reading, but not for writing. To determine whether a particular class supports thread-safe processing, check its documentation in the .NET Framework class library reference (msdn2.microsoft.com/en-us/library/ms306608.aspx).

Also recall that when a collection is modified, any enumerator returned previously by the GetEnumerator method becomes invalid and will throw an exception if its methods are invoked. Other threads may change the collection, so using an enumerator is not thread safethus, the For Each statement is not thread safe either. If you use an enumerator or a For Each statement in a multithreaded application, you should use the SyncLock statement to prevent other threads from using the collection or use a try statement to catch the InvalidOperationException.



Visual BasicR 2005 for Programmers. DeitelR Developer Series
Visual Basic 2005 for Programmers (2nd Edition)
ISBN: 013225140X
EAN: 2147483647
Year: 2004
Pages: 435

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net