有没有办法在System.Runtime.Caching中强制执行MemoryCache的大小限制?
我正在使用.NET4内存缓存。我想将缓存的大小限制在10mb,因为我不希望我的应用程序滥用其中的内容有没有办法在System.Runtime.Caching中强制执行MemoryCache的大小限制?,caching,.net-4.0,Caching,.net 4.0,我正在使用.NET4内存缓存。我想将缓存的大小限制在10mb,因为我不希望我的应用程序滥用其中的内容 我还想知道在任何给定时间我的缓存有多少内存。运行时如何判断?您可以在配置中执行此操作。。。例如 <system.runtime.caching> <memoryCache> <namedCaches> <add name="Default" cacheMemoryLimitMegabytes
我还想知道在任何给定时间我的缓存有多少内存。运行时如何判断?您可以在配置中执行此操作。。。例如
<system.runtime.caching>
<memoryCache>
<namedCaches>
<add name="Default"
cacheMemoryLimitMegabytes="52"
physicalMemoryLimitPercentage="40"
pollingInterval="00:04:01" />
</namedCaches>
</memoryCache>
</system.runtime.caching>
您可以使用元素在应用程序配置文件中指定专用于MemoryCache
的最大物理内存量,或者在创建MemoryCache
实例时,通过传递到中的NameValueCollection
传入设置,方法是在集合中输入一个键为且值为10的条目
下面是namedCaches
配置元素的示例:
<configuration>
<system.runtime.caching>
<memoryCache>
<namedCaches>
<add name="Default"
cacheMemoryLimitMegabytes="10"
physicalMemoryLimitPercentage="0"
pollingInterval="00:05:00" />
</namedCaches>
</memoryCache>
</system.runtime.caching>
</configuration>
这篇文章详细介绍了配置MemoryCache
对象的所有方法,一些示例是从这个源代码改编而来的。此时似乎无法强制执行为缓存分配的最大内存量。更多参考请参见本帖:Cool!!你也能用代码做吗?你知道如何知道缓存有多大吗?你应该能够知道,因为它需要它构造函数中的配置项。。。作为一个名值集合。你知道。。。这一切我都试过一段时间了&没能让它工作。。。我不知道为什么我给自己留了一张便条问这个问题。我将进一步调查。为什么cacheMemoryLimitMegabytes和physicalMemoryPercentage一起使用?我认为使用其中一个是合乎逻辑的。这个大小限制什么时候得到评估?添加新缓存项时,或仅在轮询间隔期间?@manipurea async根据pollingInterval
和concery=t,通过一些复杂的练习,您可以看到是否需要ILSpy
//Create a name / value pair for properties
var config = new NameValueCollection();
config.Add("pollingInterval", "00:05:00");
config.Add("physicalMemoryLimitPercentage", "0");
config.Add("cacheMemoryLimitMegabytes", "10");
//instantiate cache
var cache = new MemoryCache("CustomCache", config);