locked
Advanced Caching: Clearing all caches for all users without causing exceptions and null references RRS feed

  • Question

  • User1663022000 posted

    We have a heavily cached asp.net mvc app. It uses HttpRuntime.Cache to store its caches. The caches are stored per user by including the username in the key name during cached object creation. Now because the backend data comes from a single data store its possible that a user's update activity, could cause a need to refresh all the other users' caches. And here in lies the issue. If we purge the cache for all users, it may happen during an action that was in the middle of using one of those cached references. For example an enumeration of a cached collection. 

    Simply using a lock does not actually resolve the issue as many of the cached objects may be referenced after they have been retrieved from the cache. Initially we wanted to use object cloning to deal with this issue, but we use some heavy objects that aren't always serializable. Reference counting in .Net does not seem possible and we don't like the idea of inducing a garbage collection via GC.Collect to find the state of WeakReference.IsAlive.

    Are there any other techniques that can help in this situation? Thanks.

    Friday, March 29, 2013 12:11 AM

Answers

  • User1779161005 posted

    Why would this be an issue? A reader will get a reference to the cached it and have the reference. If some other piece of the application then purges that entry then it won't affect the other code since the other code has the reference.

    Now, if the code doing the reading is doing something like this:

    foreach(var item in Cache["foo"]) { ... }

    then the reader is written incorrectly.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, March 29, 2013 8:37 AM

All replies

  • User1779161005 posted

    Why would this be an issue? A reader will get a reference to the cached it and have the reference. If some other piece of the application then purges that entry then it won't affect the other code since the other code has the reference.

    Now, if the code doing the reading is doing something like this:

    foreach(var item in Cache["foo"]) { ... }

    then the reader is written incorrectly.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, March 29, 2013 8:37 AM
  • User1663022000 posted

    Yes you are right. When I return from the cache I am returning a reference to the object, not to the cache. So even if the cache goes away as long as the original object is alive I am ok. 

    Saturday, March 30, 2013 12:54 AM