问题
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.
回答1:
You can implement one more method TryAdd
public static bool TryAddCacheItem(string key, object data)
{
locker.EnterWriteLock();
try
{
if (cacheItems.ContainsKey(key))
{
return false;
}
cacheItems.Add(key, data);
return true;
}
finally
{
locker.ExitWriteLock();
}
}
Also I would suggest to use ConcurrentDictionary. Here is the code of the ConcurrentDictionary.
回答2:
Just execute twice:
cacheItems.Add(key, data);
...and you will know the answer. Basically the exception will be thrown and caught by the try/finally block. I would personally use the if statement rather than putting all the logic responsibility on the try block, but its a question of preference...
来源:https://stackoverflow.com/questions/11027369/how-to-correctly-handle-adding-new-item-to-dictionary