Background: I'm writing ASP.NET MVC 3 Web app. I have a List<MyObject>
(actually several lists) of objects I want to keep in cache due to handy automatic expiration feature and thread-safety.
Each of those objects internally contains instance of System.Threading.Semaphore
used for internal Server push implementation.
So I wonder how will change my objects' lifecycle if I put them into cache? May this create problems with threading/NullReferenceExceptions if cache actually disposes objects it purges/etc.? Maybe some other obvious reasons not to do this?
TIA.
The cache doesn't explicitly dispose objects when they are ejected from the cache for whatever reason. You could prove this by testing it, but if this was the case it would be in the documentation, and it isn't:
http://msdn.microsoft.com/en-us/library/system.web.caching.cache.aspx
The lifecycle of the objects in the cache may be extended by being in the cache, since the cache is holding a reference to them. If you want to avoid this you can instead cache a weak reference.
http://msdn.microsoft.com/en-us/library/system.weakreference.aspx
If you do this there should be no lifecycle implications of storing the reference in the cache.
One thing to think about - you say you want to use the cache because it is thread safe. You should be aware that the cache object itself is thread safe, but if you cache a non-thread safe object in the cache that won't make the cached object itself automatically thread safe. Specifically List<T>
is not thread safe and storing it in the cache won't change this. Use the concurrent collections if you want to ensure thread safety.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With