ASP.NET Cache bit me today

2008-03-26 @ 18:09#

ok, simple question. read the code example below. note the use of ASP.NET's Cache object, note the use of the disk file and the CacheDependency set up there. finally, note that the object stored to cache is a string array. now...

run the code in your head and answer the following questions:

at the end of the run:

  1. what are the values in memory?
  2. what are the values on disk?
  3. why?

dang-it!

using System;
using System.IO;
using System.Web;
using System.Web.Caching;

public class cacheTest : IHttpHandler
{

    public void ProcessRequest(Httpctx ctx)
    {
        string key = ctx.Server.MapPath("~/cachetest/cachetest.txt");
        string data = "item1,item2";
        string[] results = null;
        
        // check memory
        results = (string[])ctx.Cache.Get(key);
        
        if (results == null)
        {
            // check disk
            if(key.Exists(key))
            {
                // read it
                using(StreamReader sr = new StreamReader(key))
                {
                    data = sr.ReadToEnd();
                    sr.Close();
                }
            }
            else
            {
                // ok, then write it
                using(StreamWriter sw = new StreamWriter(key))
                {
                    sw.Write(data);
                    sw.Close();
                }
            }
            
            // create array
            results = data.Split(',');
            
            // store to memory
            ctx.Cache.Add(
                key, 
                results, 
                new CacheDependency(key), 
                Cache.NoAbsoluteExpiration,
                Cache.NoSlidingExpiration,
                CacheItemPriority.Normal, 
                null);
        }

        // modify array
        results[0] = "itemA";
        
        // show results
        ctx.Response.ContentType = "text/plain";
        ctx.Response.Write("results: " + results[0] + ", " + results[1]);
        
        // questions:
        // what is in memory now?
        // what is on disk now?
        // explain your answer
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

code