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

StackOverflow https://stackoverflow.com/questions/3672281

Question

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

Was it helpful?

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.

OTHER TIPS

In 5+ years of ASP.NET development projects, I've never come across a situation where this was a worry.

That being said... you're certainly not going to have a problem reading any items. If you have an object that you want to modify often, why is it in the cache to begin with? If you don't need to modify it often, then locking the object won't be a performance problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top