I have an ASP.NET application where I use static class as cache. Inside that static class is internal dictionary, which holds cached objects. Of course, in static class are methods like Add/Remove/Clear… It looks as follows:
public static class CacheManager
{
private static Dictionary<string, object> cacheItems = new Dictionary<string, object>();
private static ReaderWriterLockSlim locker = new ReaderWriterLockSlim();
public static Dictionary<string, object> CacheItems
{
get
{
return cacheItems;
}
}
public static void AddCacheItem(string key, object data)
{
locker.EnterWriteLock();
try
{
cacheItems.Add(key, data);
}
finally
{
locker.ExitWriteLock();
}
}
...
}
The items was added to the cache (dictionary) when ASP.NET application runs. I just want to ask should I check for example in Add method if key is already added in this way:
public static void AddCacheItem(string key, object data)
{
locker.EnterWriteLock();
try
{
if (!cacheItems.ContainsKey(key))
{
cacheItems.Add(key, data);
}
}
finally
{
locker.ExitWriteLock();
}
}
Or leave it as is in first code snippet?
Thank you in advance.
You can implement one more method TryAdd
Also I would suggest to use ConcurrentDictionary. Here is the code of the ConcurrentDictionary.