Arrays Synchronization

Many times, you’ll find it necessary to synchronize access to an array or a collection type that implements ICollection.4 The System.Array type implements ICollection as well as IList. One of the properties of ICollection is IsSynchronized, which always returns false for regular arrays. That’s because regular arrays aren’t synchronized by default, because enforcing such a rule would cause those who don’t need synchronization to pay a penalty. Therefore, you must manage synchronization yourself.

The easiest way to manage synchronization is via the System.Monitor class, which you normally use via the C# lock keyword. The class allows you to acquire the built-in synchronization lock on an object.5 However, instead of acquiring a lock on the array object itself, you should acquire a lock on the ICollection.SyncRoot object instead.

Many array and collection implementations are free to return a reference to the actual container via the ICollection.SyncRoot property, but they might not for various reasons. ICollection.SyncRoot provides a common way for synchronizing access to both arrays and collections.

If you are going to need synchronization within collections used in multithreaded systems, I highly suggest that you use the collection types in System.Collections.Concurrent. These types were added to .NET 4.0 by the Parallel Computing Platform team at Microsoft and their locking techniques are finely tuned for efficiency in concurrent multithreaded environments.

You can acquire a lock on any object referenced in the CLR. Each object has a lazily created sync block, which contains the lock variable that the CLR manages internally when System.Monitor attempts to acquire the lock.

Source Of Information : Apress Accelerated C Sharp 2010


Subscribe to Developer Techno ?
Enter your email address:

Delivered by FeedBurner