asp.net.ph

Array.SyncRoot Property

System Namespace   Array Class


Returns an object that can be used to synchronize access to the Array.

[ VB ]
<Serializable>
Overridable Public ReadOnly Property SyncRoot As Object _
   Implements ICollection.SyncRoot

[ C# ]
[Serializable]
public virtual object SyncRoot {get;}

[ C++ ]
[Serializable]
public: __property virtual Object* get_SyncRoot ( );

[JScript ]
public Serializable
function get SyncRoot ( ) : Object;

Property Value

An object that can be used to synchronize access to the Array.

Implements

ICollection.SyncRoot

Remarks

This property implements the System.Collections.ICollection interface.

.NET Framework classes based on Array provide their own synchronized version of the collection using the SyncRoot property.

Classes that use arrays can also implement their own synchronization using the SyncRoot property. The synchronizing code must perform operations on the SyncRoot of the collection, not directly on the collection. This ensures proper operation of collections that are derived from other objects. Specifically, it maintains proper synchronization with other threads that might be simultaneously modifying the collection. Note that some implementations of SyncRoot might return the Array itself.

Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads could still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.

The following code example shows how to lock a collection during the entire enumeration by using the SyncRoot:

[ C# ] 
Array myCollection = new int [ ];
 lock ( myCollection.SyncRoot ) {
 foreach ( Object item in myCollection ) {
 // Insert your code here.
 }
}
[ VB ] 
Dim myCollection As New Int [ ] 
Dim item As Object
SyncLock myCollection.SyncRoot
 For Each item In myCollection
 ' Insert your code here.
 Next item
End SyncLock
See Also

Array Members   IsSynchronized Skip Navigation Links




Home
Suggested Reading


Previous page Back to top Next page

© 2000-2010 Rey Nuñez All rights reserved.

If you have any question, comment or suggestion
about this site, please send us a note

You can help support asp.net.ph