码迷,mamicode.com
首页 > 编程语言 > 详细

线程安全Dictionary

时间:2015-12-24 19:11:18      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:

public abstract class ReadFreeCache<TKey, TValue>
{
    protected ReadFreeCache()
        : this(null)
    { }

    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)
    {
        TValue value;

        if (this.m_storage.TryGetValue(key, out value))
        {
            return value;
        }

        lock (this.m_writeLock)
        {
            if (this.m_storage.TryGetValue(key, out value))
            {
                return value;
            }

            value = this.Create(key);
            var newStorage = this.m_storage.ToDictionary(
                p => p.Key,
                p => p.Value,
                this.m_storage.Comparer);

            newStorage.Add(key, value);
            this.m_storage = newStorage;
        }

        return value;
    }
}
public abstract class ReadWriteCache<TKey, TValue>
{
    protected ReadWriteCache()
        : this(null)
    { }

    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)
    {
        TValue value;

        this.m_rwLock.EnterReadLock();
        try
        {
            if (this.m_storage.TryGetValue(key, out value))
            {
                return value;
            }
        }
        finally
        {
            this.m_rwLock.ExitReadLock();
        }

        this.m_rwLock.EnterWriteLock();
        try
        {
            if (this.m_storage.TryGetValue(key, out value))
            {
                return value;
            }

            value = this.Create(key);
            this.m_storage.Add(key, value);
        }
        finally
        {
            this.m_rwLock.ExitWriteLock();
        }

        return value;
    }
}

 

线程安全Dictionary

标签:

原文地址:http://www.cnblogs.com/zynbg/p/5073866.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!