【发布时间】:2014-05-13 09:07:35
【问题描述】:
我正在尝试为 C# 便携式库(.Net 4 及更高版本(Asp.net MVC、Winodws 8、Widows Phone 8、Silver light、将来可能用于 WPF)实现自定义缓存,低延迟代码,会是多线程缓存,尝试在单例上实现。怎么可能
如何使我的实现单例和线程安全。
interface ICustomCache
{
bool IsFound(string key, out value); //returns true if found the object
void Set(string key, object value); //If there is already an object with such a key, then the set should replace the old object
}
public class Cache : ICustomCache
{
private readonly Dictionary<string, object> _cacheDictionary = new Dictionary<string, object>();
public bool IsFound(string key, out object value)
{
if (_cacheDictionary.ContainsKey(key))
{
return _cacheDictionary.TryGetValue(key, out value);
}
value = null;
return false;
}
public void SetCachedObject(string key, object value)
{
if (_cacheDictionary.ContainsKey(key))
{
_cacheDictionary.Remove(key);
_cacheDictionary.Add(key,value);
}
else
{
_cacheDictionary.Add(key, value);
}
}
}
【问题讨论】:
-
这是作为练习吗?如果没有,您可以重用现有的实现,例如 Guava 的 LoadingCache。还有,为什么 c# 和 Java?
-
建议堆栈溢出,这不是练习,我正在为可移植库实现低延迟代码
-
好吧,到目前为止你已经有了一个界面。对于实施:您尝试过什么?另外:可移植类库是模棱两可的:它需要支持哪些框架?这可能很重要。
标签: c# asp.net multithreading caching