Tomer
Tomer

Reputation: 11

Using the ASP.NET thread-safe cache object with an almost read only object

I was using the cache object to hold an XMLDocument object. To be specific, the code is:

XmlDocument xDoc = new XmlDocument();
if (HttpRuntime.Cache.Get("AuthorizationXML") == null)
{
    string file = GetAuthorizationXmlFilePath();
    xDoc.Load(file);
    HttpRuntime.Cache.Insert("AuthorizationXML", xDoc, new CacheDependency(file));
}
else
{
    xDoc = (XmlDocument)HttpRuntime.Cache.Get("AuthorizationXML");
}

return xDoc;

Anyway, my team leader suggested that because cache object is thread safe, it will a waste to use it for an almost readonly object and it will be better to implement the cache object as a singleton free threaded object on application object. It this statement sounds legit? Does thread-safe means that cache object is implemented with locking, will it slow the system? Is locking even applied when just reading from cache? I'd appreciate any comment.

Upvotes: 1

Views: 4199

Answers (1)

Steven
Steven

Reputation: 172875

The ASP.NET only guarantees thread-safety around changing an item in the cache, but does not give any guarantee when changing an object it holds in the cache. So if the object you retrieve from the cache isn't immutable (=unable to change after creation), the ASP.NET cache will not protect you.

Objects that are not immutable should not be reused by multiple threads. It doesn't matter if you store it in the ASP.NET cache or some globally defined variable. Reusing mutable objects over threads is dangerous, and can lead to race conditions, in case they are (accidentally) changed.

When the object is immutable, it doesn't matter where you store it, since all threads can use it without any danger. The choice over using Cache or Global/Singleton has nothing to do with the thread-safety of an object, since both require thread-safe objects and the guarantees of the cache are pretty lame, so this doesn't help you.

The ASP.NET cache allows you to keep an item in the cache for a period of time, while a Singleton will (per definition) stay there until the AppDomain dies. So if you need the item to be refreshed more than once per AppDomain lifetime (which you show with your example by the use of the CacheDependency), than you something else than a Singleton; such as the ASP.NET cache.

Upvotes: 1

Related Questions