ASP.NET Cache Sweet Hacks
Originally published 17 Jan, 2017
The Cache in ASP.NET is a wonderful API that lets you store frequently-accessed data in-memory, so that it can be retrieved much faster in future. So instead of making that relatively-slow call to the database or hitting that API endpoint, you can get your data almost immediately.
It sounds too good to be true, yea? Just like the speed force, using the Cache comes with its own problems. In this article, Phil Karlton mentions Cache Invalidation as one of the only two hard things in Computer Science.
Cache Invalidation simply means determining when the stored data is due for a refresh. It’s difficult because, well … we can’t predict the future. The data could need a refresh in 2 minutes, or it could be valid for an entire week.
In ASP.NET, the Cache is designed to accept dynamic data, which means you can store objects of any type in it. Cool, yea?
Now, we’ll be looking at helper methods from this GitHub gist to make our Cache endeavors much shorter and more fun. Let’s look at cool stuff we can do with it.
Retrieving Data from the Cache
One of the things you’re told about the Cache is that when retrieving data, you should always assume that the data isn’t there and perform checks to make sure it’s there. e.g.
public DataTable GetCustomers(bool BypassCache)
{
string cacheKey = "CustomersDataTable";
object cacheItem = Cache[cacheKey] as DataTable;
if((BypassCache) || (cacheItem == null))
{
cacheItem = GetCustomersFromDataSource();
Cache.Insert(cacheKey, cacheItem, null, DateTime.Now.AddSeconds(GetCacheSecondsFromConfig(cacheKey),
TimeSpan.Zero);
}
return (DataTable)cacheItem;
}
How can we make this shorter and simpler?
public DataTable GetCustomers(bool byPassCache) {
return MCache.Get<DataTable>("CustomersDataTable", () => GetCustomersFromDataSource(), byPassCache);
}
Here, we make use of generics to ensure that the type returned from the Cache is what we require.
We also ensure if that if it isn’t present in the Cache, there’s a method to generate the required data to both fill the Cache and be returned.
We also ensure that we can by-pass the Cache if required.
What we’re doing is stunning three death-eaters with one wand, my dear muggle friends.
Clearing the Cache
So you’ve been storing related data in the Cache using keys with a similar pattern. Now you need to delete them all?
MCache.Clear(@"...enter regex here ...");
Or you simply need to delete the entire Cache? Why would you? Hey, it’s not my business what you get up to with your Cache …
MCache.Clear();
Now, the Cache is capable of a whole lot more. I look forward to more sweet hacks for exploring the Cache API. if you’ve got any, drop em in the comment section.