In my DataCache I need to cache an object using two indexes.
Say I cache like this:
Campaign campaign = //get campaign from db
HttpContext.Current.Cache.Add(
"Campaigns.Id."+campaign.Id.ToString(),
campaign,
null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.Normal,
null);
HttpContext.Current.Cache.Insert("Campaigns.Code."+campaign.Code,
campaign,
null,
System.Web.Caching.Cache.NoAbsoluteExpiration,
System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.Normal,
null);
I try to access the cache using either Id or Code “index”. If not found, the campaign is retrieved and indexed as shown above.
Can this method lead to any problems?
ASP can decide to remove just one of the indexes. If I access the cache through that index it will fetch the item and reindex both again and that’s ok.
UPDATE:
My main question is whether I have to pay for storing the object two times or if it a just a reference to the same object that is stored in cache?
You can make sure that both entries are removed together by using a
CacheDependencyobject. Here is the updated insert statement. That makes the expiration times no longer necessary.But in practice both variants are fine.
Edit: You should probably make the insertion of the second entry dependent on the success of adding the first entry. Consider a scenario where multiple requests ask for an object not in the cache. A typical race. All of them create the data (fine), one of them can successful call
Add(...)(fine), but all of them can successful callInsert(...)(possibly bad). You might end up with different objects returned for your two indices.I propose the following changes to your code: