C#集合类(HashTable, Dictionary, ArrayList)与HashTable线程安全

HashTable中的key/value均为object类型,由包含集合元素的存储桶组成。存储桶是 HashTable中各元素的虚拟子组,与大多数集合中进行的搜索和检索相比,存储桶可令搜索和检索更为便捷。每一存储桶都与一个哈希代码关联,该哈希代码是使用哈希函数生成的并基于该元素的键。HashTable的优点就在于其索引的方式,速度非常快。如果以任意类型键值访问其中元素会快于其他集合,特别是当数据量特别大的时候,效率差别尤其大。

HashTable的应用场合有:做对象缓存,树递归算法的替代,和各种需提升效率的场合。

  1. //Hashtable sample
  2. System.Collections.Hashtable ht = new System.Collections.Hashtable();
  3. //--Be careful: Keys can't be duplicated, and can't be null----
  4. ht.Add(1, "apple");
  5. ht.Add(2, "banana");
  6. ht.Add(3, "orange");
  7. //Modify item value:
  8. if(ht.ContainsKey(1))
  9. ht[1] = "appleBad";
  10. //The following code will return null oValue, no exception
  11. object oValue = ht[5];
  12. //traversal 1:
  13. foreach (DictionaryEntry de in ht)
  14. {
  15. Console.WriteLine(de.Key);
  16. Console.WriteLine(de.Value);
  17. }
  18. //traversal 2:
  19. System.Collections.IDictionaryEnumerator d = ht.GetEnumerator();
  20. while (d.MoveNext())
  21. {
  22. Console.WriteLine("key:{0} value:{1}", d.Entry.Key, d.Entry.Value);
  23. }
  24. //Clear items
  25. ht.Clear();

Dictionary和HashTable内部实现差不多,但前者无需装箱拆箱操作,效率略高一点。

  1. //Dictionary sample
  2. System.Collections.Generic.Dictionary<int, string> fruits =
  3. new System.Collections.Generic.Dictionary<int, string>();
  4. fruits.Add(1, "apple");
  5. fruits.Add(2, "banana");
  6. fruits.Add(3, "orange");
  7. foreach (int i in fruits.Keys)
  8. {
  9. Console.WriteLine("key:{0} value:{1}", i, fruits);
  10. }
  11. if (fruits.ContainsKey(1))
  12. {
  13. Console.WriteLine("contain this key.");
  14. }

ArrayList是一维变长数组,内部值为object类型,效率一般:

  1. //ArrayList
  2. System.Collections.ArrayList list = new System.Collections.ArrayList();
  3. list.Add(1);//object type
  4. list.Add(2);
  5. for (int i = 0; i < list.Count; i++)
  6. {
  7. Console.WriteLine(list[i]);
  8. }

HashTable是经过优化的,访问下标的对象先散列过,所以内部是无序散列的,保证了高效率,也就是说,其输出不是按照开始加入的顺序,而Dictionary遍历输出的顺序,就是加入的顺序,这点与Hashtable不同。如果一定要排序HashTable输出,只能自己实现:

  1. //Hashtable sorting
  2. System.Collections.ArrayList akeys = new System.Collections.ArrayList(ht.Keys); //from Hashtable
  3. akeys.Sort(); //Sort by leading letter
  4. foreach (string skey in akeys)
  5. {
  6. Console.Write(skey + ":");
  7. Console.WriteLine(ht[skey]);
  8. }

HashTable与线程安全:

为了保证在多线程的情况下的线程同步访问安全,微软提供了自动线程同步的HashTable:

如果 HashTable要允许并发读但只能一个线程写, 要这么创建 HashTable实例:

//Thread safe HashTable
System.Collections.Hashtable htSyn = System.Collections.Hashtable.Synchronized(new System.Collections.Hashtable());
这样, 如果有多个线程并发的企图写HashTable里面的 item, 则同一时刻只能有一个线程写, 其余阻塞; 对读的线程则不受影响。

另外一种方法就是使用lock语句,但要lock的不是HashTable,而是其SyncRoot;虽然不推荐这种方法,但效果一样的,因为源代码就是这样实现的:

  1. //Thread safe
  2. private static Hashtable htCache = new Hashtable();
  3. public static void AccessCache()
  4. {
  5. lock (htCache.SyncRoot)
  6. {
  7. //Do something
  8. }
  9. }

posted on 2011-08-29 16:24  小谈  阅读(135)  评论(0)    收藏  举报