如何正确处理添加新项目到字典? [英] How to correctly handle adding new item to dictionary?
问题描述
public static class CacheManager
{
私人静态字典< 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();
}
}
...
}
当ASP.NET应用程序运行时,项目已添加到缓存(字典)中。我只是想问我应该检查例如Add方法,如果键已经以这种方式添加:
public static void AddCacheItem (字符串键,对象数据)
{
locker.EnterWriteLock();
try
{
if(!cacheItems.ContainsKey(key))
{
cacheItems.Add(key,data);
}
}
finally
{
locker.ExitWriteLock();
}
}
或在第一个代码片段中保留它? / p>
提前谢谢。
您可以实现一种方法tryAdd
public static bool TryAddCacheItem(string key,object data)
{
locker.EnterWriteLock() ;
try
{
if(cacheItems.ContainsKey(key))
{
return false;
}
cacheItems.Add(key,data);
返回true;
}
finally
{
locker.ExitWriteLock();
}
}
另外我建议使用 ConcurrentDictionary 。 这里是ConcurrentDictionary的代码。
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
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.
这篇关于如何正确处理添加新项目到字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!