Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is HttpContext.Current.Cache thread-safe ?

Tags:

c#

.net

caching

Please check the code below:

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 && !objDDLTable.Contains("testDropDown"))
{
   arrDDLItems = GetDropDownList("testDropDown");
   objDDLTable.Add("testDropDown", arrDDLItems);
   HttpContext.Current.Cache["TestSet"] = objDDLTable;
}
else
{
   arrDDLItems = objDDLTable["testDropDown"] as DdlItem[];
}

The code, as you can infer, is basically to cache some values for a dropdown list on a web page.

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.

This works fine in most cases, however, we have got the following error occassionally :

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)

Logically, there should never be a case when the system is trying to add the key testDropDown in the HashTable when its already present, the first else condition should not allow it.

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.

In my knowledge, Cache 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?

like image 749
Danish Khan Avatar asked Jan 27 '11 16:01

Danish Khan


1 Answers

The HttpContext.Current.Cache object itself is thread safe meaning that storing and reading from it are thread safe but obviously objects that you store inside might not be thread safe. In your case you are storing a Hashtable which is not thread safe object meaning that this instance could potentially be shared between multiple threads and there could be concurrent read and writes to the hashtable and this could lead to problems.

like image 152
Darin Dimitrov Avatar answered Nov 08 '22 19:11

Darin Dimitrov