Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 261
kazuoua Avatar asked Jun 06 '13 18:06

kazuoua


People also ask

Is MemoryCache set thread safe?

MemoryCache is threadsafe. Multiple concurrent threads can read and write a MemoryCache instance.

What is runtime cache?

Runtime caching refers to gradually adding responses to a cache "as you go". While runtime caching doesn't help with the reliability of the current request, it can help make future requests for the same URL more reliable.

Is MemoryCache shared?

MemoryCache does not allow you to share memory between processes as the memory used to cache objects is bound to the application pool. That's the nature of any in-memory cache implementation you'll find. The only way to actually use a shared cache is to use a distributed cache.


1 Answers

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"); }
                      });

}
like image 86
I4V Avatar answered Oct 21 '22 10:10

I4V