title: Locking HttpRuntime.Cache for lazy loading
body: <p>We have a website running .NET 2.0 and have started using the ASP.Net HttpRuntime.Cache to store the results of frequent data lookups to cut down our database access. </p>
  
  <p>Snippet:</p>
  
  <pre> <code>
  lock (locker)
  {
      if (HttpRuntime.Cache[cacheKey] == null)
      {
          HttpRuntime.Cache.Insert(cacheKey, GetSomeDataToCache(), null, DateTime.Today.AddDays(1), Cache.NoSlidingExpiration);       
      }
      return ((SomeData)HttpRuntime.Cache[cacheKey]).Copy();
  }
  </code></pre>
  
  <p>We are pessimistically locking whenever we want to look at the cache. However, I've seen various blogs posted around the web suggesting you lock after you check the cache value instead, to not incur the overhead of the lock. That doesn't seem right as another thread may have written to the cache after the check. </p>
  
  <p>So finally my question is what is the "right" way to do this? Are we even using the right thread synchronization object? I am aware of ReaderWriterLockSlim() but we're running .NET 2.0.</p>