当使用Cache.Add,是如果键已经存在一个异常抛出或者它静静地失败了呢? [英] When using Cache.Add, is an exception thrown if the key exists already or does it fail silently?
问题描述
我已阅读无处不在的Add方法失败,如果它已经存在,但它抛出一个异常,它静静地失败了呢?
我写一个多线程的Web应用程序,它应该不存在,如果我覆盖缓存会引起问题,所以我不能使用Insert方法。
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 :)
推荐答案
的System.Web.Caching.Cache
的设计是线程安全的在多线程Web应用程序,和多线程可能会在争夺中添加相同的密钥缓存。因此,它取决于你想如何处理这样的比赛条件。
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.
-
在很多情况下,你会被插入一成不变的数据放入高速缓存,并不会在意哪个线程赢得了比赛。所以,你可以使用
添加
或插入
。
如果你想第一个赢,使用添加
方法,如果你想最后一胜(并覆盖),使用插入
方法。
If you want "first one wins", use the Add
method, if you want "last one wins (and overwrites)" use the Insert
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
nor Insert
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, and Insert
wil overwrite.
顺便说一下,从高速缓存读取时,不检查是否存在然后阅读:
Incidentally, when reading from the Cache, don't check for existence then read:
if (Cache["MyKey"] == null)
{
// ... handle missing value
}
else
{
// ... a race condition means the item may have been removed here
// before you get a chance to read it
MyType value = (MyType) Cache["MyKey"];
}
相反,读取缓存中的价值,并检查空:
Instead, read the value from the cache and check for null:
MyType value = Cache["MyKey"] as MyType; // for reference types
if (value == null)
{
// ... handle missing value
}
这篇关于当使用Cache.Add,是如果键已经存在一个异常抛出或者它静静地失败了呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!