Caching got you down? Try an Object Lock

If you are using caching in, 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

//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.

By Steve Novoselac

Director of Digital Technology @TrekBikes, Father, Musician, Cyclist, Homebrewer

Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.