
























public abstract class ReadFreeCache<TKey, TValue>
{
protected ReadFreeCache()
protected ReadFreeCache(IEqualityComparer<TKey> comparer)
this.m_storage = new Dictionary<TKey, TValue>(comparer);
public abstract TValue Create(TKey key);
private Dictionary<TKey, TValue> m_storage;
private readonly object m_writeLock = new object();
public TValue Get(TKey key)
if (this.m_storage.TryGetValue(key, out value))
if (this.m_storage.TryGetValue(key, out value))
value = this.Create(key);
var newStorage = this.m_storage.ToDictionary(
this.m_storage.Comparer);
newStorage.Add(key, value);
this.m_storage = newStorage;
}
___________________________________________________________________________
public abstract class ReadWriteCache<TKey, TValue>
{
protected ReadWriteCache()
protected ReadWriteCache(IEqualityComparer<TKey> comparer)
this.m_storage = new Dictionary<TKey, TValue>(comparer);
private readonly Dictionary<TKey, TValue> m_storage;
private readonly ReaderWriterLockSlim m_rwLock = new ReaderWriterLockSlim();
protected abstract TValue Create(TKey key);
public TValue Get(TKey key)
this.m_rwLock.EnterReadLock();
if (this.m_storage.TryGetValue(key, out value))
this.m_rwLock.ExitReadLock();
this.m_rwLock.EnterWriteLock();
if (this.m_storage.TryGetValue(key, out value))
value = this.Create(key);
this.m_storage.Add(key, value);
this.m_rwLock.ExitWriteLock();
}
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。