0

Default ASP.NET use in memory cache so it looks like it use Dictionary<> internally to use key-value pairs. But external caching solutions like Azure cache or others serialize data which makes scenarious different that in memory solution. At below example, i hold List object with key and i update it.

var users = new List<User>();
HttpContext.Cache.Insert("key", users);
users.Add(new User());//cached list will update itself with this insertion ?
var cachedUsers = (List<User>) HttpContext.Cache["key"];// now i got users list object reference or copied users list without inserted user ?

As i commented on lines, if this scenario use default in memory cache solution of ASP.NET so it is clear that cache holds users list reference but answers are changing if i use external Cache solution like Azure cache solution. What are answers of below questions if external solution is used which serialize objects instead of caching object references ?

Cached list will update itself with that insertion ?

if i get back data from cache,it would be users list object reference or copied users list without inserted user ?

Community
  • 1
  • 1
Freshblood
  • 6,285
  • 10
  • 59
  • 96

1 Answers1

3

In a cache that stores data in-memory, your user list would be updated. Obviously in a cache store that serializes the data, your user list would contain the list without the newly added user.

In any way relying on your cache values getting updated after inserting it in your cache is bad practice. What if you want to move to a different type of cache later? When the data that you're caching changes, you invalidate your cache, and re-populate it. Don't rely on the implementation.

Menno van den Heuvel
  • 1,851
  • 13
  • 24
  • What if i have scenario to add or delete list object in some scenarious so i have to update whole list in cache ? So it wouldn't be big performance impact to update very large list just for one add or delete operation ? – Freshblood Mar 13 '14 at 15:05
  • If you have a large list that needs updating often, it may simply not be a good candidate for getting cached. – Menno van den Heuvel Mar 13 '14 at 15:15
  • Have an idea to handle this scenario efficiently? – Freshblood Mar 13 '14 at 15:17
  • Maybe it isn't imperative for the data to always be up-to-date, in which case you can do a periodic update of the cache. Do you always need the entire list? Maybe you can cache items individually, or according to the subsections that you need. That way updating the cache can be both quicker and won't have to happen as often (provided you write clever invalidation logic). – Menno van den Heuvel Mar 13 '14 at 15:24