SortedList.SyncRoot 属性

定义

获取一个对象,该对象可用于同步对 SortedList 对象的访问。Gets an object that can be used to synchronize access to a SortedList object.

public:
 virtual property System::Object ^ SyncRoot { System::Object ^ get(); };
public virtual object SyncRoot { get; }
member this.SyncRoot : obj
Public Overridable ReadOnly Property SyncRoot As Object

属性值

一个对象,该对象可用于同步对 SortedList 对象的访问。An object that can be used to synchronize access to the SortedList object.

实现

示例

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

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

检索此属性的值是一个 O(1) 操作。Retrieving the value of this property is an O(1) operation.

注解

若要创建 SortedList 对象的同步版本,请使用 Synchronized 方法。To create a synchronized version of the SortedList object, use the Synchronized method. 但是,派生类可以使用 SyncRoot 属性提供其自己的 SortedList 的同步版本。However, derived classes can provide their own synchronized version of the SortedList using the SyncRoot property. 同步代码必须对 SortedListSyncRoot 执行操作,而不是直接在 SortedList上执行操作。The synchronizing code must perform operations on the SyncRoot of the SortedList, not directly on the SortedList. 这样可确保对从其他对象派生的集合正确地执行操作。This ensures proper operation of collections that are derived from other objects. 具体而言,它与可能同时修改 SortedList 对象的其他线程保持正确的同步。Specifically, it maintains proper synchronization with other threads that might be simultaneously modifying the SortedList object.

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

适用于

另请参阅