Will System.Runtime.Caching.MemoryCache dispose ID

2019-06-18 04:10发布

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?

1条回答
聊天终结者
2楼-- · 2019-06-18 04:56

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

}
查看更多
登录 后发表回答