代码之家  ›  专栏  ›  技术社区  ›  user3089358

C#内存缓存资源边界

  •  1
  • user3089358  · 技术社区  · 8 年前

    我想知道这个系统。运行时。隐藏物MemoryCache将对象封送到一个单独的资源空间,或者如果它与调用对象位于同一个资源空间中?

    例如,假设我在某个抽象对象上编写了一个helper方法,该方法允许我将对象(如DataTables)读写到缓存中:

    public static void WriteCache(string KeyName, object Item, int ExpireMinutes = 30)
    {
        ObjectCache cache = MemoryCache.Default;
        CacheItemPolicy policy = new CacheItemPolicy();
    
        policy.SlidingExpiration = new TimeSpan(0, ExpireMinutes, 0);
        policy.Priority = CacheItemPriority.Default;
    
        cache.Add(new CacheItem(KeyName, Item), policy);
    }
    

    然后将数据表发送到缓存:

    WriteCache("MY_DATA", dt, 15);
    

    1 回复  |  直到 8 年前
        1
  •  0
  •   Ben Hall    8 年前

    请注意,DataTable没有任何可处理的非托管资源( explained well in this post ).

    引用类型(如DataTable)作为对所添加对象的引用添加到MemoryCache。对象保留在相同的资源空间中。

    下面是一个简单的POCO来说明这种行为:

    class SimpleClass
        {
            public string someText { get; set; }
        }
    
        static void Main()
        {
            var cache = MemoryCache.Default;
            var simpleObject = new SimpleClass { someText = "starting text" };
            SimpleClass cachedContent = null;
    
            CacheItemPolicy policy = new CacheItemPolicy();
    
            cache.Add("mykey", simpleObject, policy);
    
            // Expect "starting text" output
            cachedContent = (SimpleClass) cache.Get("mykey");
            Console.WriteLine(cachedContent.someText);
    
            simpleObject.someText = "new text";
    
            // Now it will output "new text"
            cachedContent = (SimpleClass)cache.Get("mykey");
            Console.WriteLine(cachedContent.someText);
    
            // simpleObject points nowhere now but object still exists, 
            // pointed to by cache item so will still output "new text"
            simpleObject = null;
            cachedContent = (SimpleClass)cache.Get("mykey");
            Console.WriteLine(cachedContent.someText);
        }