I was wondering if the System.Runtime.Cache.MemoryCache marshals objects into a separate resource space, or if it resides in the same resource space as the calling object?
For instance, say I write a helper method, on some abstract object, that allows me to read and write objects (such as DataTables) to the cache:
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);
}
And then send a DataTable to the cache:
WriteCache("MY_DATA", dt, 15);
Would disposing the DataTable in the calling code, afterwards, also dispose the DataTable in the Cache? Or is the DataTables copied to the Cache (like a COM+ object, in Server Mode, when it marshals across to its resource space)?
Note that DataTable doesn't have any unmanaged resources to dispose of (explained well in this post).
Reference types (like DataTable) are added to MemoryCache as references to the object being added. Object remains in the same resource space.
Here's a trivial POCO to illustrate the behaviour:
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);
}