我正在尝试实现一个通用缓存管理器,但是我不确定如何进行锁定。
到目前为止,我有以下内容,但是如果我有两个具有相同返回类型的缓存条目,那么我猜测将使用相同的锁对象!
public class CacheManager : ICacheManager
{
static class TypeLock<T>
{
public static readonly object SyncLock = new object();
}
private readonly ICache _cache;
public CacheManager(ICache cache)
{
if (cache == null)
throw new ArgumentNullException("cache");
_cache = cache;
}
public TResult AddCache<TResult>(string cacheKey, Func<TResult> acquire, int cacheDurationInMinutes) where TResult : class
{
return AddCache(cacheKey, null, acquire, cacheDurationInMinutes);
}
public TResult AddCache<TResult>(string cacheKey, CacheDependency dependency, Func<TResult> acquire, int cacheDurationInMinutes) where TResult : class
{
var entry = acquire.Invoke();
if (entry != null)
{
if (dependency != null)
_cache.InsertWithDependency(cacheKey, entry, dependency, DateTime.Now.AddMinutes(cacheDurationInMinutes));
else
_cache.Insert(cacheKey, entry, DateTime.Now.AddMinutes(cacheDurationInMinutes));
}
return entry;
}
public TResult GetOrAddCache<TResult>(string cacheKey, Func<TResult> acquire, int cacheDurationInMinutes) where TResult : class
{
return GetOrAddCache(cacheKey, null, acquire, cacheDurationInMinutes);
}
public TResult GetOrAddCache<TResult>(string cacheKey, CacheDependency dependency, Func<TResult> acquire, int cacheDurationInMinutes) where TResult : class
{
var entry = _cache.GetItem(cacheKey) as TResult;
if (entry == null)
{
lock (TypeLock<TResult>.SyncLock)
{
entry = _cache.GetItem(cacheKey) as TResult;
if (entry == null)
{
entry = acquire.Invoke();
if (entry != null)
{
if (dependency != null)
_cache.InsertWithDependency(cacheKey, entry, dependency,
DateTime.Now.AddMinutes(cacheDurationInMinutes));
else
_cache.Insert(cacheKey, entry, DateTime.Now.AddMinutes(cacheDurationInMinutes));
}
}
}
}
return entry;
}
}
任何帮助将非常感激!