I have read everywhere that the Add method fails if it already exists but does it throw an exception or does it fail silently?
I am writing a multithreaded web application where it should not exist already and it will cause problems if I overwrite the cache, so I can't use the Insert method.
Would this be something I could do:
try
{
HttpContext.Current.Cache.Add("notifications", notifications, null,
System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromHours(8),
System.Web.Caching.CacheItemPriority.High, null);
}
catch
{
//do whatever if notifications already exist
}
Thanks for any answers :)
This is something that would be easy enough to test yourself, but it will throw an error. A good utility function to use:
Remove will not complain if the key doesn't exit. If you would like to test if the key is already there, you can always check
As long as you use a locking variable, you should not run into an issue where your check says something is NOT in the cache, and it shows up between the check and the add.
It fails silently.
The output of this console app is
Object1
.System.Web.Caching.Cache
is designed to be thread-safe in a multithreaded web application, and multiple threads may be in contention to add the same key to the cache. So it depends on how you want to handle such race conditions.In many cases, you will be inserting immutable data into the cache and won't care which thread 'wins' the race. So you can use
Add
orInsert
.If you want "first one wins", use the
Add
method, if you want "last one wins (and overwrites)" use theInsert
method.There is no point in checking for existence before inserting/adding. Another thread may insert the item after your check and before you attempt to add/insert.
Neither
Add
norInsert
with throw an exception if the key already exists. It wouldn't make sense to do so as the Cache is designed for thread-safe insertion without locking.Add
will fail silently, andInsert
wil overwrite.Incidentally, when reading from the Cache, don't check for existence then read:
Instead, read the value from the cache and check for null: