How do I clear a System.Runtime.Caching.MemoryCache

后端 未结 7 2265
隐瞒了意图╮
隐瞒了意图╮ 2020-12-09 07:16

I use a System.Runtime.Caching.MemoryCache to hold items which never expire. However, at times I need the ability to clear the entire cache. How do I do that?

相关标签:
7条回答
  • 2020-12-09 08:21

    You should not call dispose on the Default member of the MemoryCache if you want to be able to use it anymore:

    The state of the cache is set to indicate that the cache is disposed. Any attempt to call public caching methods that change the state of the cache, such as methods that add, remove, or retrieve cache entries, might cause unexpected behavior. For example, if you call the Set method after the cache is disposed, a no-op error occurs. If you attempt to retrieve items from the cache, the Get method will always return Nothing. http://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache.dispose.aspx

    About the Trim, it's supposed to work:

    The Trim property first removes entries that have exceeded either an absolute or sliding expiration. Any callbacks that are registered for items that are removed will be passed a removed reason of Expired.

    If removing expired entries is insufficient to reach the specified trim percentage, additional entries will be removed from the cache based on a least-recently used (LRU) algorithm until the requested trim percentage is reached.

    But two other users reported it doesnt work on same page so I guess you are stuck with Remove() http://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache.trim.aspx

    Update However I see no mention of it being singleton or otherwise unsafe to have multiple instances so you should be able to overwrite your reference.

    But if you need to free the memory from the Default instance you will have to clear it manually or destroy it permanently via dispose (rendering it unusable).

    Based on your question you could make your own singleton-imposing class returning a Memorycache you may internally dispose at will.. Being the nature of a cache :-)

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