Hashtable.IsSynchronized 屬性

定義

取得值,這個值表示對 Hashtable 的存取是否同步 (安全執行緒)。

C#
public virtual bool IsSynchronized { get; }

屬性值

如果 true 的存取為同步 (安全執行緒),則為 Hashtable,否則為 false。 預設為 false

實作

範例

下列範例示範如何同步處理 Hashtable、判斷 是否已 Hashtable 同步處理 ,以及使用已同步處理的 Hashtable

C#
using System;
using System.Collections;

public class SamplesHashtable2
{
    public static void Main()
    {
        // Creates and initializes a new Hashtable.
        var myHT = new Hashtable();
        myHT.Add(0, "zero");
        myHT.Add(1, "one");
        myHT.Add(2, "two");
        myHT.Add(3, "three");
        myHT.Add(4, "four");

        // Creates a synchronized wrapper around the Hashtable.
        Hashtable mySyncdHT = Hashtable.Synchronized(myHT);

        // Displays the sychronization status of both Hashtables.
        Console.WriteLine("myHT is {0}.", myHT.IsSynchronized ? "synchronized" : "not synchronized");
        Console.WriteLine("mySyncdHT is {0}.", mySyncdHT.IsSynchronized ? "synchronized" : "not synchronized");
    }
}

/*
This code produces the following output.

myHT is not synchronized.
mySyncdHT is synchronized.
*/

備註

Hashtable可以同時支援一個寫入器和多個讀取器。 若要支援多個寫入器,所有作業都必須透過 方法傳回的 Synchronized 包裝函式來完成。

透過集合列舉本質上不是安全線程程式。 即使集合經過同步化,其他的執行緒仍可修改該集合,使列舉值擲回例外狀況。 若要保證列舉過程的執行緒安全,您可以在整個列舉過程中鎖定集合,或攔截由其他執行緒的變更所造成的例外狀況。

下列程式代碼範例示範如何在整個列舉期間使用 SyncRoot 鎖定集合:

C#
var myCollection = new Hashtable();
lock (myCollection.SyncRoot)
{
    foreach (object item in myCollection)
    {
        // Insert your code here.
    }
}

適用於

產品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1
UWP 10.0

另請參閱