Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpRuntime.Cache best practices

Tags:

In the past I have put a lock around accessing the HttpRuntime.Cache mechanism. I'm not sure if I had really researched the issue in the past and blindy surrounded it with a lock.

Do you think this is really necessary?

like image 693
Andrew Harry Avatar asked Apr 16 '09 03:04

Andrew Harry


2 Answers

This article suggests a lock should be used:

http://msdn.microsoft.com/en-us/magazine/cc500561.aspx

Quote:

The problem is that if you've got a query that takes 30 seconds and you're executing the page every second, in the time it takes to populate the cache item, 29 other requests will come in, all of which will attempt to populate the cache item with their own queries to the database. To solve this problem, you can add a thread lock to stop the other page executions from requesting the data from the database.

Here is their code snippet:

// check for cached results
object cachedResults = ctx.Cache["PersonList"];
ArrayList results = new ArrayList();

if  (cachedResults == null)
{
  // lock this section of the code
  // while we populate the list
  lock(lockObject)
  {
    cachedResults = ctx.Cache["PersonList"];
    // only populate if list was not populated by
    // another thread while this thread was waiting
    if (cachedResults == null)
    {
      cachedResults = ...
      ctx.Cache["PersonList"] = cachedResults;
    }
  }
}

I haven't tested this code, but I would be very interested to hear someone who has evaluated this approach in a production environment.

like image 184
frankadelic Avatar answered Oct 14 '22 08:10

frankadelic


According to this documentation http://msdn.microsoft.com/en-us/library/system.web.caching.cache(VS.80).aspx access to the cache object is thread safe. As for the object(s) you store in the cache thread safety has to come from somewhere else.

like image 41
j3r03nq Avatar answered Oct 14 '22 09:10

j3r03nq