title: Caching global data in an iis website
body: <p>I have  READONLY object graph that is cached for one minute so that it can be used by all threads (Code below).  </p>
  
  <pre><code>public class ObjectGraphCache
  {
      static readonly Object storeLock = new object();
  
      public ObjectGraph AllForElection(int ElectionId, System.Web.Caching.Cache cache)
      {
          string key=string.Format("AllForElection{0}",
              ElectionId);
          int timout = int.Parse(ConfigurationManager.AppSettings["dbCacheTimeInSeconds"]);
  
          if (timout == 0)
          {
              ObjectGraph graph = new ObjectGraph();
              graph.AllForElection(ElectionId);
              return graph;
          }
          else
          {
              Object obj = cache[key];
              if (obj == null)
              {
                  lock (storeLock)
                  {
                      obj = cache[key]; // In case another page got the lock first and your are queued (Ensures only one get per cycle)
                      if (obj == null)
                      {
                          // Not in cache
                          ObjectGraph graph = new ObjectGraph();
                          graph.AllForElection(ElectionId);
  
                          cache.Insert(
                              key,
                              graph,
                              null,
                              DateTime.Now.Add(new TimeSpan(0, 0, timout)),
                              System.Web.Caching.Cache.NoSlidingExpiration);
                          return graph;
                      }
                  }
              }
              return (ObjectGraph)obj;
          }
  </code></pre>
  
  <p>However I want to know : Why use the Cache object, when I more easily store the READONLY object as a static.  This stores a pointer to the heap, so when it is updated, threads still processing the previous pointers object will carry one fine with the old object, AND also I would not have to cast the object from the cache before returning it.  Anyone see any gotchas?</p>