gpt4 book ai didi

c# - HttpRuntime.Cache 最佳实践

转载 作者:IT王子 更新时间:2023-10-29 04:39:03 26 4
gpt4 key购买 nike

过去,我对访问 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com