毕业论文开发语言企业开发JAVA技术.NET技术WEB开发Linux/Unix数据库技术Windows平台移动平台嵌入式论文范文英语论文
您现在的位置: 毕业论文 >> net技术 >> 正文

多线程访问list报错

更新时间:2013-1-5:  来源:毕业论文

多线程访问list报错
请教大家一个问题

多线程访问并修改单利里的数据到底是否线程安全?是否同步?

我在单利中有一个List对象,多个线程多其进行添加或修改操作,我发现有时候会报错,提示多线程访问有冲。迷茫了...
哪位神仙指点一下

public static class PermanentCache
    {
        static Dictionary<string, object> cache = new Dictionary<string, object>();
        static ReaderWriterLockSlim readWriteLock = new ReaderWriterLockSlim();

        public static object GetObject(string key)
        {
            object retValue;
            try
            {
                readWriteLock.EnterReadLock();
                cache.TryGetValue(key, out retValue);
            }
            finally
            {
                readWriteLock.ExitReadLock();
            }
            return retValue;
        }
public static void Set(string key, object obj)
        {
            readWriteLock.EnterUpgradeableReadLock();
            try
            {
                object result;
                if (cache.TryGetValue(key, out result))
                {
                    if (result != obj)
                    {
                        readWriteLock.EnterWriteLock();
                        try
                        {
                            cache[key] = obj;
                        }
                        finally
                        {
                            readWriteLock.ExitWriteLock();
                        }
                    }
                }
                else
                {
                    readWriteLock.EnterWriteLock();
                    try
                    {
                        cache.Add(key, obj);
                    }
                    finally
                    {
                        readWriteLock.ExitWriteLock();
                    }
                }
            }
            finally
            {
                readWriteLock.ExitUpgradeableReadLock();
            }
        }
}

设为首页 | 联系站长 | 友情链接 | 网站地图 |

copyright©youerw.com 优尔论文网 严禁转载
如果本毕业论文网损害了您的利益或者侵犯了您的权利,请及时联系,我们一定会及时改正。