在C#/ .Net中缓存

Seb*_*ler 32 .net c# caching

我想问你在C#中实现缓存的最佳方法是什么?是否有可能使用给定的.NET类或类似的东西?也许类似于字典会删除一些条目,如果它变得太大,但哪些条目不会被垃圾收集器删除?

小智 28

如果您使用的是.NET 4或更高版本,则可以使用MemoryCache类.


Bra*_*vax 16

如果您使用的是ASP.NET,则可以使用Cacheclass(System.Web.Caching).

这是一个很好的帮助类:c-cache-helper-class

如果您的意思是在Windows窗体应用程序中缓存,则取决于您尝试执行的操作以及尝试缓存数据的位置.

对于某些方法
(使用System.Web.Caching对象),我们在Web服务后面实现了一个缓存.

但是,您可能还想查看缓存应用程序块.(请参阅此处),它是.NET Framework 2.0企业库的一部分.

  • 它没有说他使用asp.net (2认同)
  • 我建议使用 asp.net 的选项以及不使用时的方法。(缓存应用程序块)。 (2认同)

ala*_*ree 5

框架中的MemoryCache是一个很好的起点,但您可能还想考虑开源库LazyCache,因为它具有比内存缓存更简单的 API,并且内置了锁定以及一些其他开发人员友好的功能。它也可以在 nuget 上找到。

给你一个例子:

// 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 的作者)

  • 这不是对内存缓存的巨大更改,而是处理并发问题并减少了一行可兑现委托的重复。多次编写相同的粗略代码为我拥有一个库节省了时间,这对我来说已经足够了。 (2认同)