use*_*r_v 5 c# caching httpruntime.cache
我想为某些键存储null,HttpRuntime.Cache因为我不想再次转到数据库以找到该键没有条目.
所以第一次,它进入数据库并填充缓存.目的是使用缓存数据而不是进行数据库调用来提供以下调用.
这是我使用以下代码:
Info info = null;
if (HttpRuntime.Cache["Info_" + id.ToString() + "_" + quantity.ToString()] != null)
info = HttpRuntime.Cache["Info_" + id.ToString() + "_" + quantity.ToString()] as Info;
if (info == null)
{
info = (from dd in dc.Infos
where dd.id == id && dd.active == true && dd.quantitytooffset == quantity
select dd).SingleOrDefault();
HttpRuntime.Cache.Add("Info_" + id.ToString() + "_" + quantity.ToString(), info, null, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.High, null);
}
Run Code Online (Sandbox Code Playgroud)
最后一行代码即HttpRuntime.Cache.Add抛出一个System.ArgumentNullException:Value不能为null.
任何想法是否可行或我需要使用其他数据结构来存储空值并在以后查找?
您可以使用自己的"null"值放入缓存中.例如,
private static Info NULL_INFO = new Info();
Run Code Online (Sandbox Code Playgroud)
那么你可以在HttpRuntime.Cache.Add中使用它而不是null,然后在从缓存检索后检查你没有得到你的NULL_INFO
if ( info == NULL_INFO) // if you don't have equality operator overloaded, otherwise you'd better use ReferenceEquals()
// return empty data
else if (info == null)
// proceed with try to load from database
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4251 次 |
| 最近记录: |