ReadOnlyCollectionBase.ICollection.SyncRoot 属性

定义

获取一个对象,该对象可用于同步对 ReadOnlyCollectionBase 对象的访问。

property System::Object ^ System::Collections::ICollection::SyncRoot { System::Object ^ get(); };
object System.Collections.ICollection.SyncRoot { get; }
member this.System.Collections.ICollection.SyncRoot : obj
 ReadOnly Property SyncRoot As Object Implements ICollection.SyncRoot

属性值

一个对象,该对象可用于同步对 ReadOnlyCollectionBase 对象的访问。

实现

示例

下面的代码示例演示如何在整个枚举期间使用 SyncRoot 属性锁定集合。

// Get the ICollection interface from the ReadOnlyCollectionBase
// derived class.
ICollection^ myCollection = myReadOnlyCollection;
bool lockTaken = false;
try
{
    Monitor::Enter(myCollection->SyncRoot, lockTaken);
    for each (Object^ item in myCollection);
    {
        // Insert your code here.
    }
}
finally
{
    if (lockTaken)
    {
        Monitor::Exit(myCollection->SyncRoot);
    }
}
// Get the ICollection interface from the ReadOnlyCollectionBase
// derived class.
ICollection myCollection = myReadOnlyCollection;
lock(myCollection.SyncRoot)
{
    foreach (object item in myCollection)
    {
        // Insert your code here.
    }
}
' Get the ICollection interface from the ReadOnlyCollectionBase
' derived class.
Dim myCollection As ICollection = myReadOnlyCollection
SyncLock myCollection.SyncRoot
    For Each item As Object In myCollection
        ' Insert your code here.
    Next item
End SyncLock

检索此属性的值是一项 O(1) 操作。

注解

派生类可以使用 属性提供自己的类的同步版本ReadOnlyCollectionBaseSyncRoot。 同步代码必须对 SyncRoot 对象的 属性 ReadOnlyCollectionBase 执行操作,而不是直接对 对象执行 ReadOnlyCollectionBase 操作。 这样可确保对从其他对象派生的集合正确地执行操作。 具体而言,它与可能同时修改 ReadOnlyCollectionBase 对象的其他线程保持适当的同步。

枚举整个集合本质上不是一个线程安全的过程。 即使某个集合已同步,其他线程仍可以修改该集合,这会导致枚举数引发异常。 若要确保枚举过程中的线程安全性,可以在整个枚举期间锁定集合,或者捕获由其他线程进行的更改所导致的异常。

适用于

另请参阅