我有一个网站,我在那里缓存了很多信息.我看到有关在asp.net缓存中存储东西的相互矛盾的信息.
例如,假设我有这样的数据结构:
Dictionary<string, List<Car>> mydictionary;
Run Code Online (Sandbox Code Playgroud)
我可以使用字符串键将整个事物存储为"MyDictionary",然后在我拉出对象时向下钻取.
HttpContext.Cache.Add("MyDictionary",
mydictionary,
null,
Cache.NoAbsoluteExpiration,
new TimeSpan(10, 0, 0),
CacheItemPriority.Normal,
null);
var myDict = HttpContext.Cache["MyDictionary"] as Dictionary<string, List<Car>>;
Run Code Online (Sandbox Code Playgroud)
我能做的另一件事是将其分解并将我的字典中的每个项目分别存储在缓存中(无论如何缓存都是字典).
Dictionary<string, List<Car>> mydictionary;
foreach (var item in mydictionary.Keys)
{
HttpContext.Cache.Add(item, mydictionary[item], null, Cache.NoAbsoluteExpiration, new TimeSpan(10, 0, 0), CacheItemPriority.Normal, null);
}
var myitem = "test";
var myDict = HttpContext.Cache[myItem] as List<Car>;
Run Code Online (Sandbox Code Playgroud)
性能含义是否会非常不同(假设我假设一切都在内存中?)
我有一个运行MVC 3 c#的网站从web服务中提取记录.随着它从Web服务获取的数据集变得越来越大,我正在寻找一种方法,在没有当前缓存的情况下,第一个用户不会在没有当前缓存的情况下触发创建缓存,而是按日计划(像cron工作,计划任务或其他).
我该怎么做?我是否需要某种类似Quartz.net的触发器库?(我宁愿使用更简单的解决方案)
我现在在控制器中拥有的是:
private List<DataSummary> GetSummaries()
{
//get summaries from cache if available
List<DataSummary> summaries = (List<DataSummary>)HttpContext.Cache["SummariesCache"];
if (summaries == null)
{
//cache empty, retrieve values
summaries = _webservice.GetSummaries();
//cache it
HttpContext.Cache.Add("SummariesCache", summaries, null, DateTime.Now.AddHours(12), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
}
return summaries;
}
Run Code Online (Sandbox Code Playgroud)
编辑
使用CacheItemRemovedCallback
导致超时错误
我有以下代码来缓存一些昂贵的代码.
private MyViewModel GetVM(Params myParams)
{
string cacheKey = myParams.runDate.ToString();
var cacheResults = HttpContext.Cache[cacheKey] as MyViewModel ;
if (cacheResults == null)
{
cacheResults = RunExpensiveCodeToGenerateVM(myParams);
HttpContext.Cache[cacheKey] = cacheResults;
}
return cacheResults;
}
Run Code Online (Sandbox Code Playgroud)
这将永远留在缓存中吗?直到服务器重新启动或内存不足?
是否有任何好的工具可以查看我的数据量(甚至更好的数据)HttpContext.Cache
?
这个HttpContext
类Cache
和Items
属性有什么区别?
从MSDN文档:
Cache
获取当前应用程序域的Cache对象.Items
获取一个键/值集合,可用于在HTTP请求期间在IHttpModule接口和IHttpHandler接口之间组织和共享数据.
我真的不明白该文档试图解释什么.
在处理ASP.NET Web应用程序时,我经常使用Items
每个请求的数据缓存,这样多个用户控件最终不会从数据库中查找相同的数据.这篇文章对此进行了描述.
今天,我遇到了Cache
属性的用法,看起来像每个请求缓存.我试图理解差异,但找不到比较这两者的任何好的文件.所以我想知道......
HttpContext的Cache和Items属性有什么区别?请尝试详细说明为什么在不同的真实场景中选择使用其中一个的示例.