Is there a way to enforce a size limit of MemoryCache in System.Runtime.Caching?

后端 未结 3 1713
囚心锁ツ
囚心锁ツ 2021-02-02 11:32

I\'m using .net 4 Memory Cache. I would like to limit the size of the cache say to 10mb because I don\'t want my application to be abusing what goes in there.

I would al

相关标签:
3条回答
  • 2021-02-02 11:55

    It seems at this time the maximum amount of memory allocated for the cache can not be enforced. See this post for further reference: MemoryCache does not obey memory limits in configuration

    0 讨论(0)
  • 2021-02-02 11:59

    You can do this in configuration... for example...

    <system.runtime.caching>
       <memoryCache>
          <namedCaches>
             <add name="Default"
                  cacheMemoryLimitMegabytes="52"
                  physicalMemoryLimitPercentage="40"
                  pollingInterval="00:04:01" />
          </namedCaches>
       </memoryCache>
    </system.runtime.caching>
    

    To do this in code see... this msdn page

    0 讨论(0)
  • 2021-02-02 12:18

    You can specify the maximum amount of physical memory dedicated to the MemoryCache in the application config file using the namedCaches element, or by passing in the setting when you create your MemoryCache instance via the NameValueCollection passed into the constructor by putting an entry in the collection with a key of cacheMemoryLimitMegabytes and a value of 10.

    Here is an example of the namedCaches configuration element:

    <configuration>
      <system.runtime.caching>
        <memoryCache>
          <namedCaches>
            <add name="Default" 
              cacheMemoryLimitMegabytes="10" 
              physicalMemoryLimitPercentage="0"
              pollingInterval="00:05:00" />
          </namedCaches>
        </memoryCache>
      </system.runtime.caching>
    </configuration>
    

    And here is how you can configure the MemoryCache during creation:

    //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);
    

    This blog post details just about all of the ways to configure the MemoryCache object, and some examples were adapted from this source.

    0 讨论(0)
提交回复
热议问题