Tuesday, January 18, 2011

Listing the contents of the MemoryCache

MemoryCache is a replacement for the System.Web.Caching.Cache class (think HttpRuntime.Cache) that has been provided in .Net 4.0 and above (thus allowing you to get rid of the dependency on System.Web).

The GetEnumerator is not a publicly available method on the MemoryCache class and so you need to first cast it to an IEnumerable and use it to enumerate over the contents of the Cache. The enumerator returned is a IDictionaryEnumerator enumerator.

MemoryCache memoryCache = MemoryCache.Default;
IDictionaryEnumerator cacheEnumerator = (IDictionaryEnumerator)((IEnumerable)memoryCache).GetEnumerator();
           Conosle.WriteLine("{0} : {1}{2}", cacheEnumerator.Key , cacheEnumerator.Value, Environment.NewLine);

1 comment:

Flemming Appelon Christiansen said...

Thank you for this post, have been looking for this method!