.NET 4 缓存支持
本文关键字:支持 缓存 NET | 更新日期: 2023-09-27 17:56:19
我知道.NET 4框架内置了缓存支持。有没有人对此有任何经验,或者可以提供很好的资源来了解更多信息?
我指的是在内存中缓存对象(主要是实体),可能还有System.Runtime.Caching的使用。
我假设你正在得到这个,System.Runtime.Caching
,类似于System.Web.Caching
,并且在更通用的命名空间中。
见 http://deanhume.com/Home/BlogPost/object-caching----net-4/37
在堆栈上,
系统运行时缓存中存在某种缓存依赖关系,
系统运行时缓存的性能。
可能有用。
我自己没有使用它,但是如果您只是在内存中缓存简单的对象,则可能指的是System.Runtime.Caching命名空间中的MemoryCache类。在页面末尾有一个如何使用它的小示例。
编辑:为了让它看起来像我实际上已经为这个答案做了一些工作,这是该页面的示例! :)
private void btnGet_Click(object sender, EventArgs e)
{
ObjectCache cache = MemoryCache.Default;
string fileContents = cache["filecontents"] as string;
if (fileContents == null)
{
CacheItemPolicy policy = new CacheItemPolicy();
List<string> filePaths = new List<string>();
filePaths.Add("c:''cache''example.txt");
policy.ChangeMonitors.Add(new
HostFileChangeMonitor(filePaths));
// Fetch the file contents.
fileContents =
File.ReadAllText("c:''cache''example.txt");
cache.Set("filecontents", fileContents, policy);
}
Label1.Text = fileContents;
}
这很有趣,因为它表明您可以将依赖项应用于缓存,就像在经典 ASP.NET 缓存中一样。这里最大的区别在于您不依赖于 System.Web 程序集。
中的MemoryCache是一个很好的起点,但你可能也想考虑LazyCache,因为它有一个比内存缓存更简单的API,并且内置了锁定以及其他一些不错的功能。它在 nuget 上可用:PM> Install-Package 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);
我最近写了这篇关于在 dot net 中开始缓存的文章,您可能会发现它很有用。
(免责声明:我是LazyCache的作者)
希望您指的是 的 System.Runtime.Caching 。网络框架 4.0
下面的链接是一个很好的起点:这里
MSDN 文章"ASP.NET 缓存:技术和最佳实践"是一个很好的开始。