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

后端 未结 7 2308
隐瞒了意图╮
隐瞒了意图╮ 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:20

    I ran into this problem too. .Dispose() did something quite different than what I expected.

    Instead, I added a static field to my controller class. I did not use the default cache, to get around this behavior, but created a private one (if you want to call it that). So my implementation looked a bit like this:

    public class MyController : Controller
    {
    
        static MemoryCache s_cache = new MemoryCache("myCache");
    
        public ActionResult Index()
        {
    
            if (conditionThatInvalidatesCache)
            {
                s_cache = new MemoryCache("myCache");
            }
    
            String s = s_cache["key"] as String;
    
            if (s == null)
            {
                //do work
                //add to s_cache["key"]
            }
    
            //do whatever next
        }
    }
    

提交回复
热议问题