13

I want to retrieve all the cache objects that are added using MemoryCache.

I tried the below but it is not retrieving them

System.Web.HttpContext.Current.Cache.GetEnumerator();
System.Web.HttpRuntime.Cache.GetEnumerator();

Note: Retreive all means not just what i know and created, i mean every cache object that gets created in the application.

1
  • 1
    I'm a biti confused by your latest edit. If this answers the question then this really should be added as an answer, not edited into the question. I appreciate that rene told you to edit it into the question but I suspect he didn't realise that it was an answer. Sorry that you are getting mixed messages! :) Commented Jun 19, 2015 at 22:13

4 Answers 4

24

This is what i found (it may help some one)

foreach (var item in MemoryCache.Default)
{
   //add the item.keys to list
}
return list;
Sign up to request clarification or add additional context in comments.

Comments

9

Here is a better way to enumerate and get the result:

public virtual List<T> GetCache<T>()
{
    List<T> list = new List<T>();
    IDictionaryEnumerator cacheEnumerator = (IDictionaryEnumerator)((IEnumerable)Cache).GetEnumerator();

    while (cacheEnumerator.MoveNext())
        list.Add((T) cacheEnumerator.Value);

    return list;
}

Comments

6

This should also work: MemoryCache.Default.ToList();

Comments

0
private static readonly Type MemoryCacheType = typeof(MemoryCache);
private static readonly FieldInfo CoherentStateFieldInfo = MemoryCacheType.GetField("_coherentState", BindingFlags.NonPublic | BindingFlags.Instance);
private static Type _coherentStateType;

var coherentState = CoherentStateFieldInfo.GetValue(memoryCache);
var coherentStateType = _coherentStateType ??= coherentState?.GetType();
var propertyInfo = coherentStateType!.GetProperty("EntriesCollection", BindingFlags.NonPublic | BindingFlags.Instance)!;

if (propertyInfo.GetValue(coherentState) is not ICollection colecao)
    yield break;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.