【发布时间】:2018-07-02 14:21:11
【问题描述】:
这是 ConcurrentDictionary ThreadSafe 吗?
private static ConcurrentDictionary<string, DateTime> dictionary= new ConcurrentDictionary<string, DateTime>();
public bool TextInputRecently(string text)
{
dictionary = new ConcurrentDictionary<string, DateTime>( dictionary.Where(pair => pair.Value.Ticks >= DateTime.Now.AddMinutes(-5).Ticks)
.ToDictionary(pair => pair.Key,
pair => pair.Value));
if (dictionary.ContainsKey(text))
return true;
dictionary.TryAdd(text, DateTime.Now);
return false;
}
我认为这不是因为在另一个线程正在检查密钥是否存在时可以重新创建字典。
在字典中循环删除过期值会更好吗?
【问题讨论】:
-
也许您正在寻找的是缓存,例如
MemoryCache。它是线程安全的并且可以处理过期问题,因此您不必检查条目日期或“手动”删除过期条目。
标签: c#