Caching got you down? Try an Object Lock

If you are using caching in ASP.net, and when your cache invalidates, you see some really bad performance or race conditions, you probably need to implement object locks.

Object myObjectLock = new object();
//Use the lock statement to ensure that only one request

lock (myObjectLock)
{
//check again if the cache is not populated by another request
if (HttpRuntime.Cache["myCacheKey"] == null)
{
DataTable cacheValue = GetDataFromDatabase();

//remove the cache key
HttpRuntime.Cache.Remove("myCacheKey");

//insert into the cache
HttpRuntime.Cache.Insert("myCacheKey", cacheValue, null, DateTime.Now.AddHours(8), TimeSpan.Zero);
}
}

Now, when your cache is rebuilt, you will avoid race conditions and bad performance on your site/database.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s