Is it OK to use HttpRuntime.Cache outside ASP.NET

2019-01-31 05:59发布

Scott Hanselman says yes.

Adding System.Web to your non-web project is a good way to get folks to panic. Another is adding a reference to Microsoft.VisualBasic in a C# application. Both are reasonable and darned useful things to do, though.

MSDN says no.

The Cache class is not intended for use outside of ASP.NET applications. It was designed and tested for use in ASP.NET to provide caching for Web applications. In other types of applications, such as console applications or Windows Forms applications, ASP.NET caching might not work correctly.

So what should I think?

标签: .net caching
8条回答
男人必须洒脱
2楼-- · 2019-01-31 06:46

There doesn't seem to be anything in current versions of System.Web.Caching.Cache that depend on the HTTP runtime except for the Insert() method that accepts a CacheItemUpdateCallback, so Scott is right for the most part.

This doesn't prevent Microsoft from modifying the class in the future to be more integrated with the HTTP infrastructure.

I wrote a WeakReference-based lightweight cache in another answer.

查看更多
Emotional °昔
3楼-- · 2019-01-31 06:53

I once used it, but it didn't feel right and IIRC increased the memory footprint quite dramatically. Instead, I implemented my own lightweight cache mechanism which is surprisingly easy to do.

It utilized the WeakReference class which allowed the cache to keep references to the object, but also allows the Garbage Collector to reclaim the memory if the reference is unused.

The only thing I didn't have was a separate thread to clean up stale items in the cache. What I did do is if the cache had > x items in it, I would go through all the cached items and turf out the old items before adding the new item.

If you need something more robust, use something like the MS Enterprise Library Caching Application Block.

查看更多
登录 后发表回答