Does System.Web.Caching.Cache Dispose of cache-cleared objects?

Reference Information. I am writing an ASP.NET MVC 3 web application. I have a List<MyObject> (in fact, several lists) of objects that I want to cache because of the convenient function of automatic expiration and thread safety.

Each of these internal objects contains an instance of System.Threading.Semaphore , used for the internal implementation of the push server.

It’s so interesting how the life cycle of my objects will change if I put them in the cache? Could this create problems with threading / NullReferenceExceptions if there are actually objects in the cache that it clears / etc? Maybe some other obvious reasons for not doing this?

TIA.

+7
source share
1 answer

The cache does not explicitly provide objects if they are thrown out of the cache for any reason. You can prove it by testing it, but if it were, it would be in the documentation, and it is not:

http://msdn.microsoft.com/en-us/library/system.web.caching.cache.aspx

The life cycle of objects in the cache can be extended by being in the cache, because the cache stores a link to them. If you want to avoid this, you can cache the weak link instead.

http://msdn.microsoft.com/en-us/library/system.weakreference.aspx

If you do this, there should be no consequences for storing the link in the cache.

What you should think about - you say that you want to use the cache because it is thread safe. You should know that the cache object itself is thread safe, but if you cache an insecure object in the cache that does not automatically make the cached object a safe thread. In particular, List<T> not thread safe, and storing it in the cache will not change it. Use parallel collections if you want to ensure thread safety.

+9
source

All Articles