c# - HttpRuntime.Cache 最佳实践

标签 c# httpruntime.cache

过去,我对访问 HttpRuntime.Cache 机制设置了锁定。 我不确定我过去是否真的研究过这个问题并盲目地用一把锁把它包围起来。

您认为这真的有必要吗?

最佳答案

这篇文章建议应该使用锁:

http://msdn.microsoft.com/en-us/magazine/cc500561.aspx

引用:

The problem is that if you've got a query that takes 30 seconds and you're executing the page every second, in the time it takes to populate the cache item, 29 other requests will come in, all of which will attempt to populate the cache item with their own queries to the database. To solve this problem, you can add a thread lock to stop the other page executions from requesting the data from the database.

这是他们的代码片段:

// 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;
    }
  }
}

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

关于c# - HttpRuntime.Cache 最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/754661/

相关文章:

c# - C# 在同一个套接字上发送+接收数据

c# - 在代码隐藏中将模型数组绑定(bind)到 View 模型

c# - 带多个 View 的 Winforms MVP 模式

javascript - 跟踪 ASP.net MVC Web 应用程序中的注销时间

c# - 查看缓存在System.Web.HttpRuntime.Cache中的数据

c# - HttpRuntime.Cache 的范围

asp.net - 我可以在应用程序之间共享 HttpRuntime.Cache 吗?

c# - 我的车辆代码有什么问题?

asp.net - iisExpress 本地 httpruntime.cache 始终为 null