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

て烟熏妆下的殇ゞ 提交于 2019-12-08 17:01:11

问题


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:


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

}


来源:https://stackoverflow.com/questions/16969321/will-system-runtime-caching-memorycache-dispose-idisposable-items-when-evicted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!