锁定HttpRuntime.Cache进行延迟加载 [英] Locking HttpRuntime.Cache for lazy loading

查看:91
本文介绍了锁定HttpRuntime.Cache进行延迟加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个运行.NET 2.0的网站,并且已经开始使用ASP.Net HttpRuntime.Cache存储频繁数据查找的结果以减少对数据库的访问.

We have a website running .NET 2.0 and have started using the ASP.Net HttpRuntime.Cache to store the results of frequent data lookups to cut down our database access.

摘要:

 
lock (locker)
{
    if (HttpRuntime.Cache[cacheKey] == null)
    {
        HttpRuntime.Cache.Insert(cacheKey, GetSomeDataToCache(), null, DateTime.Today.AddDays(1), Cache.NoSlidingExpiration);       
    }
    return ((SomeData)HttpRuntime.Cache[cacheKey]).Copy();
}

每当我们要查看缓存时,我们都会悲观地锁定.但是,我看到在网络上发布了许多博客,建议您在检查缓存值之后将其锁定,以免产生锁定的开销.这似乎不正确,因为检查后可能有另一个线程已将其写入高速缓存.

We are pessimistically locking whenever we want to look at the cache. However, I've seen various blogs posted around the web suggesting you lock after you check the cache value instead, to not incur the overhead of the lock. That doesn't seem right as another thread may have written to the cache after the check.

所以最后我的问题是做到这一点的正确"方法是什么?我们是否还在使用正确的线程同步对象?我知道ReaderWriterLockSlim(),但是我们正在运行.NET 2.0.

So finally my question is what is the "right" way to do this? Are we even using the right thread synchronization object? I am aware of ReaderWriterLockSlim() but we're running .NET 2.0.

推荐答案

据我所知,Cache对象是线程安全的,因此您不需要锁.

As far as I know the Cache object is thread safe so you wouldn't need the lock.

这篇关于锁定HttpRuntime.Cache进行延迟加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆