Hashtable.SyncRoot 屬性

定義

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

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

屬性值

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

實作

備註

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

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

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

適用於

另請參閱