c# - 为什么我应该只在应用程序生命周期的早期创建 MemoryCache?

标签 c# .net caching memorycache

根据 MSDN 文档 here :

Do not create MemoryCache instances unless it is required. If you create cache instances in client and Web applications, the MemoryCache instances should be created early in the application life cycle. You must create only the number of cache instances that will be used in your application, and store references to the cache instances in variables that can be accessed globally. For example, in ASP.NET applications, you can store the references in application state. If you create only a single cache instance in your application, use the default cache and get a reference to it from the Default property when you need to access the cache.

它并没有完全解释这背后的原因和其他几个关于清除 MemoryCache 的问题,但似乎还没有得出可靠的结论。据我所知,我的选择是处置 MemoryCache 并创建一个新实例,根据上述文档不建议这样做,或者使用枚举器,由于性能问题也不建议这样做. Trim() 已被证明是不可靠的,因此我正在研究为什么在我的应用程序生命周期中间实例化一个 MemoryCache 被认为是一个坏主意。

为了深入了解我好奇的原因,这里手头的主要问题是我希望我的 MemoryCache 仅在一系列方法调用的范围内工作。这些方法调用是在同一对象的不同实例之间进行的,这些实例共享通过数据库检索的数据,尽管可能性很小,但可能会在我分配给过期窗口的短短几秒钟内发生变化。我的想法是每当我开始一系列方法调用时创建一个新的 MemoryCache 实例,以确保我拥有最新的数据,同时不会为每个实例多次访问数据库。但是,MSDN 也建议不要创建新实例,并建议将所有实例都放在全局变量中。

所以简而言之,为什么建议在应用程序生命周期开始时实例化一个MemoryCache,为什么我应该全局引用MemoryCache我用什么?

最佳答案

因为它需要连续的内存。你想在内存碎片化之前完成它。

我不知道全局。

关于c# - 为什么我应该只在应用程序生命周期的早期创建 MemoryCache?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26788204/

相关文章:

c# - 将树结构数据转换为 XML——性能问题

c# - Excel.Worksheet.Cells[row,col] = "=Formula"与 Range.set_Value(Missing.Value, arrayFormulas)

c# - C# 如何删除字符串的第一个和最后一个字符?

c# - ASP.NET API 无法在 Azure 上发布

.net - .NET WebBrowser 控件新窗口上的 Javascript Window.Opener 对象为空

c# - 如何将图表更改为列渐变填充样式?

c# - 如何使应用程序设置独立于 .exe 路径?

javascript - 我应该将 $(document).height() 和/或 $(window).height() 存储为变量吗?

python - 禁用 python 文件的 Apache 缓存

python - 如何在django中利用浏览器缓存