将System.Runtime.Caching.MemoryCache处置IDisposable的项目拆迁户何时? [英] Will System.Runtime.Caching.MemoryCache dispose IDisposable items when evicted?

查看:283
本文介绍了将System.Runtime.Caching.MemoryCache处置IDisposable的项目拆迁户何时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个创建实施IDisposable的实例的生成器类。每当打造的产品已经在缓存中,建造者将返回实例,而不是。我的问题是,将缓存呼吁IDisposable的项目Dispose()方法包含当他们被驱逐或做我必须明确地对代码回调CacheItemPolicy.RemovedCallback这种行为?

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?

推荐答案

没有的Dispose 不叫。它很容易测试

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

}

这篇关于将System.Runtime.Caching.MemoryCache处置IDisposable的项目拆迁户何时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆