ICollection.IsSynchronized ICollection.IsSynchronized ICollection.IsSynchronized ICollection.IsSynchronized Property

定义

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

public:
 property bool IsSynchronized { bool get(); };
public bool IsSynchronized { get; }
member this.IsSynchronized : bool
Public ReadOnly Property IsSynchronized As Boolean

属性值

如果对 true 的访问是同步的(线程安全),则为 ICollection;否则为 falsetrue if access to the ICollection is synchronized (thread safe); otherwise, false.

注解

SyncRoot 返回一个对象,该对象可用于同步对 ICollection 的访问。SyncRoot returns an object, which can be used to synchronize access to the ICollection.

中的大多数集合类System.Collections命名空间还实现提供同步的包装基础集合已同步方法。Most collection classes in the System.Collections namespace also implement a Synchronized method, which provides a synchronized wrapper around the underlying collection.

枚举整个集合本质上不是一个线程安全的过程。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.

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

ICollection^ myCollection = someCollection;
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);
    }
}
ICollection myCollection = someCollection;
lock(myCollection.SyncRoot)
{
    foreach (object item in myCollection)
    {
        // Insert your code here.
    }
}
Dim myCollection As ICollection = someCollection
SyncLock myCollection.SyncRoot
    For Each item In myCollection
        ' Insert your code here.
    Next item
End SyncLock

适用于

另请参阅