HttpRuntime.Cache最佳实践

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)

我没有测试过这段代码,但是我很想听听有人在生产环境中评估过这种方法.

  • 我不认为这在缓存线程安全性方面是必要的 - 更多的是防止多次访问数据库以运行可能昂贵的查询. (11认同)
  • 在示例中只是一个小但重要的问题:在lock(lockObject)和if(cachedResults == null)之间,应该再次检索缓存的项目.有关正确的示例,请参阅http://stackoverflow.com/questions/39112/what-is-the-best-way-to-lock-cache-in-asp-net. (5认同)

小智 8

根据此文档http://msdn.microsoft.com/en-us/library/system.web.caching.cache(VS.80).aspx访问缓存对象是线程安全的.对于存储在缓存中的对象,线程安全必须来自其他地方.