ArrayList.SyncRoot 屬性

定義

取得可用以同步存取 ArrayList 的物件。Gets an object that can be used to synchronize access to the ArrayList.

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

屬性值

可用以同步存取 ArrayList 的物件。An object that can be used to synchronize access to the ArrayList.

實作

範例

下列程式碼範例示範如何使用整個列舉期間的 SyncRoot 來鎖定集合。The following code example shows how to lock the collection using the SyncRoot during the entire enumeration.

ArrayList^ myCollection = gcnew ArrayList();
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);
    }
}
ArrayList myCollection = new ArrayList();

lock(myCollection.SyncRoot)
{
    foreach (object item in myCollection)
    {
        // Insert your code here.
    }
}
Dim myCollection As New ArrayList()

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.

備註

若要建立 ArrayList的同步處理版本,請使用 Synchronized 方法。To create a synchronized version of the ArrayList, use the Synchronized method. 不過,衍生類別可以使用 SyncRoot 屬性,來提供自己的 ArrayList 同步處理版本。However, derived classes can provide their own synchronized version of the ArrayList using the SyncRoot property. 同步處理常式代碼必須在 ArrayListSyncRoot 上執行作業,而不是直接在 ArrayList上執行。The synchronizing code must perform operations on the SyncRoot of the ArrayList, not directly on the ArrayList. 如此可確保衍生自其他物件的集合可以正常運作,This ensures proper operation of collections that are derived from other objects. 具體而言,它會與其他可能同時修改 ArrayList 物件的執行緒保持適當的同步處理。Specifically, it maintains proper synchronization with other threads that might be simultaneously modifying the ArrayList 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.

適用於

另請參閱