.NET 4缓存支持

Hos*_*146 32 .net c# caching

我理解.NET 4 Framework内置了缓存支持.有没有人有这方面的经验,或者可以提供很好的资源来了解更多相关信息?

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

Jod*_*ell 27

我假设你正在使用,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,

性能系统运行时缓存.

可能有用.


Mik*_*tly 15

我自己没有使用它,但是如果你只是在内存中缓存简单对象,那么你可能在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;
}
Run Code Online (Sandbox Code Playgroud)

这很有趣,因为它表明您可以将依赖项应用于缓存,就像在经典的ASP.NET缓存中一样.这里最大的区别是你没有对System.Web程序集的依赖.


ala*_*ree 5

框架中的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);
Run Code Online (Sandbox Code Playgroud)

我最近写了一篇关于在dot net开始使用缓存的文章,你可能会发现它很有用.

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