C# MemoryCache 资源边界

C# MemoryCache Resource Boundaries

我想知道 System.Runtime.Cache.MemoryCache 是否将对象封送到单独的资源 space 中,或者它是否与调用对象驻留在同一资源 space 中?

例如,假设我在某个抽象对象上编写了一个辅助方法,它允许我读取对象(例如 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+ 对象,在服务器模式下,当它编组到其资源时 space)?

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

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

这里有一个简单的 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);
    }