📌  相关文章
📜  C#|检查HybridDictionary是否已同步(线程安全)

📅  最后修改于: 2021-05-30 01:27:25             🧑  作者: Mango

HybridDictionary.IsSynchronized属性用于获取一个值,该值指示HybridDictionary是否已同步(线程安全)。

句法:

public bool IsSynchronized { get; }

返回值:该属性始终返回false

下面的程序说明了HybridDictionary.IsSynchronized属性的用法:

范例1:

// C# code to check whether the
// HybridDictionary is synchronized
// (thread safe).
using System;
using System.Collections;
using System.Collections.Specialized;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a HybridDictionary named myDict
        HybridDictionary myDict = new HybridDictionary();
  
        // Adding key/value pairs in myDict
        myDict.Add("I", "first");
        myDict.Add("II", "second");
        myDict.Add("III", "third");
        myDict.Add("IV", "fourth");
        myDict.Add("V", "fifth");
  
        // To check whether the HybridDictionary
        // is synchronized (thread safe).
        Console.WriteLine(myDict.IsSynchronized);
    }
}

输出:

False

范例2:

// C# code to check whether the
// HybridDictionary is synchronized
// (thread safe).
using System;
using System.Collections;
using System.Collections.Specialized;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a HybridDictionary named myDict
        HybridDictionary myDict = new HybridDictionary();
  
        // Adding key/value pairs in myDict
        myDict.Add("key1", "value1");
        myDict.Add("key2", "value2");
        myDict.Add("key3", "value3");
        myDict.Add("key4", "value4");
        myDict.Add("key5", "value5");
  
        // To check whether the HybridDictionary
        // is synchronized (thread safe).
        Console.WriteLine(myDict.IsSynchronized);
    }
}

输出:

False

注意:通过集合进行枚举本质上不是线程安全的过程。即使同步了一个集合,其他线程仍然可以修改该集合,这将导致枚举器引发异常。为了保证枚举期间的线程安全,您可以在整个枚举期间锁定集合,也可以捕获由其他线程进行的更改导致的异常。

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.specialized.hybriddictionary.issynchronized?view=netframework-4.7.2