『臥槽』意外にもHashtableのforeach用法BUGを発見

6814 ワード

この間、会社のプロジェクトで問題が発生し、最後にHashtableの使い方によるものであることが判明しました.
 
 1         private static void AutoCleanCache()
 2         {
 3             try
 4             {
 5                 lock (m_HashCache.SyncRoot)
 6                 {
 7                     List<object> listKey = new List<object>();
 8                     Liststring, DateTime, byte[]>> list = new Liststring, DateTime, byte[]>>();
 9                     if (m_HashCache.Count >= MAXCACHE)
10                     {
11                         //foreach (KeyValuePair pair in m_HashCache)  //       Hashtable ——      :            
12                         foreach (object key in m_HashCache.Keys)
13                         {
14                             object value = m_HashCache[key];
15                             var svg = key as string;
16                             var bytes = value as Tuplebyte[]>;
17                             if (string.IsNullOrWhiteSpace(svg) || (bytes == null || bytes.Item2 == null || bytes.Item2.Length <= 0)) listKey.Add(key);
18 
19                             list.Add(new Tuple<string, DateTime, byte[]>(svg, (bytes == null ? DateTime.MinValue : bytes.Item1), (bytes == null ? null : bytes.Item2)));
20                         }
21                     }
22 
23                     Liststring, DateTime, byte[]>> list2 = Enumerable.ToList(list.OrderBy(x => x.Item2).Take(list.Count / 2));
24                     foreach (var item in list2) listKey.Add(item.Item1);
25                     foreach (var key in listKey) m_HashCache.Remove(key);
26 
27                     listKey.Clear();
28                     list.Clear();
29                     list2.Clear();
30                 }
31             }
32             catch (Exception ex)
33             {
34                 logger.Warn(ex);
35             }
36         }

 
コードが醜い--気にしないでください.
重点コードだけを見てみましょう.
1 //foreach (KeyValuePair pair in m_HashCache) //       Hashtable ——      :            
2 foreach (object key in m_HashCache.Keys)

 
結論:
Hashtable foreach KeyValuePair
 
 
これでいいです.私のところには底辺のコードが山積みになっています.
 
転載先:https://www.cnblogs.com/shuxiaolong/p/Hashtable_Foreach_BUG.html