And*_*rry 20 c# httpruntime.cache
在过去,我已经锁定了访问HttpRuntime.Cache机制.我不确定我过去是否真的研究过这个问题,盲人用锁把它围起来.
你觉得这真的有必要吗?
fra*_*lic 10
本文建议使用锁:
http://msdn.microsoft.com/en-us/magazine/cc500561.aspx
引用:
问题是,如果你有一个需要30秒的查询并且你每秒都在执行页面,那么在填充缓存项目所需的时间内,将有29个其他请求进入,所有这些请求都会尝试填充具有自己对数据库的查询的缓存项.要解决此问题,可以添加线程锁以阻止其他页面执行从数据库请求数据.
这是他们的代码片段:
// check for cached results
object cachedResults = ctx.Cache["PersonList"];
ArrayList results = new ArrayList();
if (cachedResults == null)
{
// lock this section of the code
// while we populate the list
lock(lockObject)
{
cachedResults = ctx.Cache["PersonList"];
// only populate if list was not populated by
// another thread while this thread was waiting
if (cachedResults == null)
{
cachedResults = ...
ctx.Cache["PersonList"] = cachedResults;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我没有测试过这段代码,但是我很想听听有人在生产环境中评估过这种方法.
小智 8
根据此文档http://msdn.microsoft.com/en-us/library/system.web.caching.cache(VS.80).aspx访问缓存对象是线程安全的.对于存储在缓存中的对象,线程安全必须来自其他地方.
| 归档时间: |
|
| 查看次数: |
23498 次 |
| 最近记录: |