gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:48:55 25 4
gpt4 key购买 nike

根据 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/

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