【问题标题】:C# MemoryCache Resource BoundariesC# MemoryCache 资源边界
【发布时间】:2017-11-07 18:55:21
【问题描述】:

我想知道 System.Runtime.Cache.MemoryCache 是否将对象编组到单独的资源空间中,或者它是否与调用对象位于同一资源空间中?

例如,假设我在某个抽象对象上编写了一个辅助方法,它允许我将对象(例如 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);
}

然后发送一个DataTable到缓存中:

WriteCache("MY_DATA", dt, 15);

会不会在调用代码中释放DataTable,之后,也会在Cache中释放DataTable?还是将 DataTables 复制到缓存中(就像 COM+ 对象,在服务器模式下,当它编组到其资源空间时)?

【问题讨论】:

    标签: c# caching com+ memorycache


    【解决方案1】:

    请注意,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);
        }
    

    【讨论】:

      猜你喜欢
      • 2010-09-08
      • 1970-01-01
      • 2020-05-26
      • 1970-01-01
      • 1970-01-01
      • 2014-06-14
      • 1970-01-01
      • 1970-01-01
      • 2010-10-04
      相关资源
      最近更新 更多