views:

27

answers:

2

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

A: 

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.

Bryan
suppose this is a domain data object. the object is not modified often, but suppose it was modified by first thread while the second thread was reading it, the first thread then will save the object to the Database.
Karim
locking locks all code even the one that only read the object. there is a way to lock writters but its not as simple as lock.this is why locking will cause threads to block even on reads.
Karim
@Karim - @Bryan is right. Objects in the cache should be readonly. But, if you absolutely must modify this objects - what about implementing the getters/setters with the singleton pattern?
RPM1984
A: 

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.

Phil Bennett