ReadOnlyCollectionBase.ICollection.IsSynchronized 属性

定义

获取一个值,该值指示对 ReadOnlyCollectionBase 对象的访问是否同步(线程安全)。Gets a value indicating whether access to a ReadOnlyCollectionBase object is synchronized (thread safe).

property bool System::Collections::ICollection::IsSynchronized { bool get(); };
bool System.Collections.ICollection.IsSynchronized { get; }
System.Collections.ICollection.IsSynchronized
 ReadOnly Property IsSynchronized As Boolean Implements ICollection.IsSynchronized

属性值

如果对 true 对象的访问是同步的(线程安全),则为 ReadOnlyCollectionBase;否则为 falsetrue if access to the ReadOnlyCollectionBase object is synchronized (thread safe); otherwise, false. 默认值为 falseThe default is false.

实现

示例

下面的代码示例演示如何在整个枚举过程中使用 SyncRoot 属性锁定集合。The following code example shows how to lock the collection using the SyncRoot property during the entire enumeration.

// 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) 操作。Retrieving the value of this property is an O(1) operation.

注解

ReadOnlyCollectionBase 对象不同步。A ReadOnlyCollectionBase object is not synchronized. 派生类可以使用 SyncRoot 属性提供 ReadOnlyCollectionBase 类的同步版本。Derived classes can provide a synchronized version of the ReadOnlyCollectionBase class using the SyncRoot property.

枚举整个集合本质上不是一个线程安全的过程。Enumerating through a collection is intrinsically not a thread-safe procedure. 即使某个集合已同步,其他线程仍可以修改该集合,这会导致枚举数引发异常。Even when a collection is synchronized, other threads can 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.

适用于

另请参阅