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

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

    The details in @stefan's answer detail the principle; here's how I'd do it.

    One should synchronise access to the cache whilst recreating it, to avoid the race condition of client code accessing the cache after it is disposed, but before it is recreated.

    To avoid this synchronisation, do this in your adapter class (which wraps the MemoryCache):

    public void clearCache() {
      var oldCache = TheCache;
      TheCache = new MemoryCache("NewCacheName", ...);
      oldCache.Dispose();
      GC.Collect();
    }
    

    This way, TheCache is always in a non-disposed state, and no synchronisation is needed.

提交回复
热议问题