我知道.NET 4框架中内置了缓存支持。有没有人有这方面的经验,或者可以提供很好的资源来了解更多?
我指的是对象(主要是实体)在内存中的缓存,可能还有System.Runtime.Caching的使用。
发布于 2011-05-12 21:25:03
我假设您使用的是this、System.Runtime.Caching,它类似于System.Web.Caching,并且使用了更通用的名称空间。
请参阅http://deanhume.com/Home/BlogPost/object-caching----net-4/37
在堆栈上,
is-there-some-sort-of-cachedependency-in-system-runtime-caching和,
performance-of-system-runtime-caching。
可能会很有用。
发布于 2011-05-12 21:30:18
我自己并没有使用过它,但是如果您只是在内存中缓存简单的对象,那么您可能会引用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程序集。
发布于 2016-05-30 22:39:58
框架中的MemoryCache是一个很好的起点,但您可能也会考虑LazyCache,因为它具有比内存缓存更简单的应用程序接口,并且具有内置的锁定以及其他一些不错的特性。它可以在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);我最近写了一篇关于getting started with caching in dot net的文章,你可能会发现这篇文章很有用。
(免责声明:我是LazyCache的作者)
https://stackoverflow.com/questions/5978482
复制相似问题