Search code examples
c#cachingidisposable

Will System.Runtime.Caching.MemoryCache dispose IDisposable items when evicted?


I have a builder class that creates an instance implementing IDisposable. Whenever the item to build is already in the cache, the builder will return that instance instead. My question is, will the cache call the Dispose() method on the IDisposable items it contains when they are evicted or do I have to explicitly code that behavior on the callback CacheItemPolicy.RemovedCallback?


Solution

  • No Dispose is not called. It is easy to test.

    public class TestClass : IDisposable
    {
        public void Dispose()
        {
            Console.WriteLine("disposed");
        }
    }
    
    MemoryCache _MemoryCache = new MemoryCache("TEST");
    
    void Test()
    {
        _MemoryCache.Add("key",
                          new TestClass(),
                          new CacheItemPolicy()
                          {
                              AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(10),
                              RemovedCallback = (_) => { Console.WriteLine("removed"); }
                          });
    
    }