HttpContext.Cache and lock

  • Thread starter Thread starter Mat
  • Start date Start date
M

Mat

Hi,

I've stumbled onto a problem when using the caching object in ASP.Net.

I'm placing a static dataset to the cache as the data only changes
once a day. Whilst writing to the cache I'm using a lock using code
like below (just typed this in);

Cache thisCache = HttpContext.Current.Cache
lock(thisCache)
{
thisCache.Insert(....)
}

When reading from the cache I'm using

Dataset a = HttpContext.Current.Cache[cacheKey]
if (a==null)
{
// Info doesnt exist...Go and create the data and write it to the
cache!
}
else
{
//I've got the info...
}



All appears to work great...until the system is placed under load -
then strange things occur. For example a empty dataset is returned
(not a null dataset but a dataset which contains the dataset schema
but has no data)

Do anyone have any ideas? I've been informed by MS that the Cache
object is meant to be thread safe, so in theory the lock isn't even
required.

Cheers,

Mat
 
Hi mat,
Have you set the expiration time for the caching. What is the
expiration time you have set for the cache?..What i suspect is, when the
cache duration that has been mentioned gets exceeded, the dataset gets
removed and the problem arises.
 
Any chance that the code pulling the DataSet out of the cache does any
manipulations?
 
the HttpContext Cache lifetime is only for the current request. it used
mainly to pass context info between modules, during ta single request. this
means you are building the dataset on every page request, so you probably
have a bug under load.

note: the cache are thread safe in that setting and getting an object from
the cache is thread safe, it does not make accessing properties on the
cached objects thread safe. also code like:

Dataset a = HttpContext.Current.Cache[cacheKey];
if (a==null)
{
// Info doesnt exist...Go and create the data and write it to the
cache!
}
else
{
//I've got the info...
}

while threadsafe, in race conditions multiple threads could detect the
object not in the cache, build and insert it, with the last thread writing
to the cache winning.

-- bruce (sqlwork.com)
 
the HttpContext Cache lifetime is only for the current request. it used
mainly to pass context info between modules, during ta single request. this
means you are building the dataset on every page request, so you probably
have a bug under load.

bruce: I believe you are thinking of the HttpContext.Items collection.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top