我已经在任何地方读过Add方法失败,如果它已经存在但它是否会抛出异常或者它是否会以静默方式失败?
我正在编写一个多线程的Web应用程序,它应该不存在,如果我覆盖缓存会导致问题,所以我不能使用Insert方法.
这是我能做的事情:
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
}
Run Code Online (Sandbox Code Playgroud)
谢谢你的回答:)
我们有一个运行.NET 2.0的网站,并开始使用ASP.Net HttpRuntime.Cache来存储频繁数据查找的结果,以减少我们的数据库访问.
片段:
lock (locker)
{
if (HttpRuntime.Cache[cacheKey] == null)
{
HttpRuntime.Cache.Insert(cacheKey, GetSomeDataToCache(), null, DateTime.Today.AddDays(1), Cache.NoSlidingExpiration);
}
return ((SomeData)HttpRuntime.Cache[cacheKey]).Copy();
}
Run Code Online (Sandbox Code Playgroud)
每当我们想要查看缓存时,我们都会悲观地锁定.但是,我已经看到网上发布的各种博客建议您在检查缓存值后锁定,以免产生锁定开销.这似乎不正确,因为另一个线程可能在检查后写入缓存.
所以最后我的问题是这样做的"正确"方法是什么?我们甚至使用正确的线程同步对象吗?我知道ReaderWriterLockSlim(),但我们正在运行.NET 2.0.