asp.netcachinghttpcontext.cacheasp.net-cache

what techniques should be used to handle objects in asp.net Cache to prevent problems from multiple asp.net worker threads access?


since asp.net contains multiple threads that are executing at the same time.
so if 2 threads access an object (simple or complex) that i got from the the asp.net httpcontext Cache.
can't this lead to state problems on that object if these 2 theads tried to modify/read it at the same time?
so what kind of precautions should i implement?
for example i am thinking maybe locking the object while working with it? (wont this cause performance problems?)
or maybe when i retrieve some object from the cache i should create a copy from it?
or maybe i dont need to worry about this issue at all?
thanks


Solution

  • You need to decide this based on the context of your problem, a one size fits all solution won't work here. If you are only reading data, then you will have no threading issues. If you are writing data to this frequently, its pointless using the cache. If its a bit of a mixture and caching does help with performance etc, then you either need to resort to normal thread synchronisation techniques (e.g. reader writer locks) or perhaps make your object immutable where changes to your object always create a new object. That choice leads to threading problems of its own as the new object has to then replace the old object in cache.