C# .NET4缓存支持

C# .NET4缓存支持,c#,.net,caching,C#,.net,Caching,我知道.NET4框架内置了缓存支持。有没有人有这方面的经验,或者可以提供很好的资源来了解更多这方面的信息 我指的是对象(主要是实体)在内存中的缓存,可能还有System.Runtime.caching的使用。MSDN文章是一个很好的开始。我想您已经了解了,类似于System.Web.caching和更通用的名称空间 看 在堆栈上 以及 可能有用。希望您指的是.Netframework 4.0的System.Runtime.Caching 下面的链接是一个很好的起点: 我自己没有使用过它,但是如

我知道.NET4框架内置了缓存支持。有没有人有这方面的经验,或者可以提供很好的资源来了解更多这方面的信息


我指的是对象(主要是实体)在内存中的缓存,可能还有System.Runtime.caching的使用。

MSDN文章是一个很好的开始。

我想您已经了解了,类似于
System.Web.caching
和更通用的名称空间

在堆栈上

以及


可能有用。

希望您指的是.Netframework 4.0的System.Runtime.Caching

下面的链接是一个很好的起点:

我自己没有使用过它,但是如果您只是在内存中缓存简单对象,那么您可能指的是System.Runtime.caching命名空间中的类。在这一页的末尾有一个关于如何使用它的小例子

编辑:为了让它看起来像我已经为这个答案做了一些工作,下面是该页面的示例!:)

private void btnGet\u单击(对象发送者,事件参数e)
{
ObjectCache=MemoryCache.Default;
string fileContents=缓存[“fileContents”]作为字符串;
if(fileContents==null)
{
CacheItemPolicy policy=新的CacheItemPolicy();
列表文件路径=新列表();
添加(“c:\\cache\\example.txt”);
policy.ChangeMonitors.Add(新建
HostFileChangeMonitor(文件路径));
//获取文件内容。
文件内容=
File.ReadAllText(“c:\\cache\\example.txt”);
Set(“filecontents”、filecontents、policy);
}
Label1.Text=文件内容;
}

这很有趣,因为它表明您可以将依赖项应用于缓存,就像在经典的ASP.NET缓存中一样。这里的最大区别是,您对系统没有依赖性。Web组件。

MyMyCache在框架中是一个很好的起点,但您可能也想考虑一下,因为它具有比内存缓存更简单的API,并内置了锁以及一些其他漂亮的特性。它可在nuget上获得:

PM>安装软件包LazyCache

// Create our cache service using the defaults (Dependency injection ready).
// Uses MemoryCache.Default as default so cache is shared between instances
IAppCache cache = new CachingService();

// Declare (but don't execute) a func/delegate whose result we want to cache
Func<ComplexObjects> complexObjectFactory = () => methodThatTakesTimeOrResources();

// Get our ComplexObjects from the cache, or build them in the factory func 
// and cache the results for next time under the given key
ComplexObject cachedResults = cache.GetOrAdd("uniqueKey", complexObjectFactory);
//使用默认值(依赖项注入就绪)创建缓存服务。
//使用MemoryCache.Default作为默认值,以便在实例之间共享缓存
IAppCache cache=new CachingService();
//声明(但不执行)要缓存其结果的func/delegate
Func complexObjectFactory=()=>methodThatTakesTimeOrResources();
//从缓存中获取ComplexObject,或在factory func中构建它们
//并将结果缓存在给定密钥下,以备下次使用
ComplexObject cachedResults=cache.GetOrAdd(“uniqueKey”,ComplexObject工厂);
我最近写了这篇文章,你可能会发现它很有用


(免责声明:我是LazyCache的作者)

缓存什么?您是指实体框架、WCF还是应用服务器?
System.Runtime.Caching
显然;-)如果尚未升级到.NET 4.5,您应该注意以下错误:说明如何避免缓存时常见的陷阱,并在它提供的示例中具体使用。我使用了此错误,但发现缺少文档。我的理解是,基本上可以像使用System.Web缓存一样使用它。
// Create our cache service using the defaults (Dependency injection ready).
// Uses MemoryCache.Default as default so cache is shared between instances
IAppCache cache = new CachingService();

// Declare (but don't execute) a func/delegate whose result we want to cache
Func<ComplexObjects> complexObjectFactory = () => methodThatTakesTimeOrResources();

// Get our ComplexObjects from the cache, or build them in the factory func 
// and cache the results for next time under the given key
ComplexObject cachedResults = cache.GetOrAdd("uniqueKey", complexObjectFactory);