title: Is HttpContext.Current.Cache thread-safe ?
body: <p>Please check the code below: </p>
  
  <pre><code>objDDLTable = HttpContext.Current.Cache["TestSet"] as Hashtable;
  
  if (objDDLTable == null)
  {
     objDDLTable = new Hashtable();
     arrDDLItems = GetDropDownList("testDropDown");
     objDDLTable.Add("testDropDown", arrDDLItems);
     HttpContext.Current.Cache["TestSet"] = objDDLTable;
  }
  else if (objDDLTable != null &amp;&amp; !objDDLTable.Contains("testDropDown"))
  {
     arrDDLItems = GetDropDownList("testDropDown");
     objDDLTable.Add("testDropDown", arrDDLItems);
     HttpContext.Current.Cache["TestSet"] = objDDLTable;
  }
  else
  {
     arrDDLItems = objDDLTable["testDropDown"] as DdlItem[];
  }
  </code></pre>
  
  <p>The code, as you can infer, is basically to cache some values for a dropdown list on a web page. </p>
  
  <p>First, it tries to read a HashTable object from the cache, then checks if the specific key exists in HashTable object read from the cache. If it does, the value (array of items) is read, else, it reads the array from the source and adds a new key in the HashTable, which is then stored back to the cache for subsequent usage.</p>
  
  <p>This works fine in most cases, however, we have got the following error occassionally : </p>
  
  <pre><code>System.ArgumentException: Item has already been added. 
  Key in dictionary: 'testDropDown' Key being added: 'testDropDown' at 
  System.Collections.Hashtable.Insert(Object key, Object nvalue, Boolean add) at 
  System.Collections.Hashtable.Add(Object key, Object value)
  </code></pre>
  
  <p>Logically, there should never be a case when the system is trying to add the key <code>testDropDown</code> in the HashTable when its already present, the first else condition should not allow it.</p>
  
  <p>The only thing that comes to my mind is a possiblility of another thread adding the key to the HashTable at a time when the condition check has failed on the first thread and it also attemps to add the key.</p>
  
  <p>In my knowledge, <code>Cache</code> is a thread safe static object, but I can't think of anything else causing that error. Can you guys please help me identify the cause here?</p>