HttpRuntime.Cache 最佳实践
过去,我对 HttpRuntime.Cache 机制的访问设置了锁定。 我不确定我过去是否真正研究过这个问题,并盲目地用锁包围了它。
您认为这真的有必要吗?
In the past I have put a lock around accessing the HttpRuntime.Cache mechanism.
I'm not sure if I had really researched the issue in the past and blindy surrounded it with a lock.
Do you think this is really necessary?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
本文建议应使用锁:
http://msdn.microsoft.com /en-us/magazine/cc500561.aspx
引用:
这是他们的代码片段:
我还没有测试过这段代码,但我非常有兴趣听到有人在生产环境中评估了这种方法。
This article suggests a lock should be used:
http://msdn.microsoft.com/en-us/magazine/cc500561.aspx
Quote:
Here is their code snippet:
I haven't tested this code, but I would be very interested to hear someone who has evaluated this approach in a production environment.
根据此文档 http:// msdn.microsoft.com/en-us/library/system.web.caching.cache(VS.80).aspx 对缓存对象的访问是线程安全的。
至于存储在缓存中的对象,线程安全必须来自其他地方。
According to this documentation http://msdn.microsoft.com/en-us/library/system.web.caching.cache(VS.80).aspx access to the cache object is thread safe.
As for the object(s) you store in the cache thread safety has to come from somewhere else.
我认为没有必要用锁包装对 HttpRuntime.Cache 属性的访问,因为 .Cache 属性是静态的并且也是线程安全的。
访问 Cache 对象的方式有很多种(HttpRuntime.Cache、HttpContext.Current.Cache、Page.Cache 等)。 它们都访问同一个 Cache 对象,因为每个应用程序域只有一个 Cache 对象,因为它实际上是一个线程安全的 Singleton 对象。
I don't think it's necessary to wrap access to the HttpRuntime.Cache property with a lock, as the .Cache property is static and also thread-safe.
There are many different ways of accessing the Cache object (HttpRuntime.Cache, HttpContext.Current.Cache, Page.Cache etc.). They all access the same Cache object, as there's only one Cache object per Application Domain, as it's effectively a thread-safe Singleton object.
我不认为锁定是下面问题的答案,特别是在生产环境中,您有多个服务器运行您的应用程序。
问题是,如果您有一个需要 30 秒的查询,并且每秒都执行该页面,那么在填充缓存项的时间内,将会有 29 个其他请求进入,所有这些请求都会尝试填充缓存项有自己的数据库查询。 为了解决这个问题,您可以添加线程锁来阻止其他页面执行向数据库请求数据。
I don't think locking is the answer to the issue below, especially in the production environment, where you have several servers running your application.
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.