views:

1729

answers:

5

Is there a way to look through the cache for all objects in the cache? I'm dynamically creating objects and I need to periodically go through the list to purge out objects I'm no longer using.

+1  A: 

Yes, you can either index based on the cache key, you you can iterate over the contents:

For Each c In Cache
    ' Do something with c
Next
' Pardon  my VB syntax if it's wrong
John Saunders
Why the downvote? I can't improve if you don't tell me where I'm wrong.
John Saunders
+2  A: 

You can enumerate through the objects:

 System.Web.HttpContext.Current.Cache.GetEnumerator()
Tom Ritter
+3  A: 

Here is a VB function to iterate through the Cache and return a DataTable representation.

Private Function CreateTableFromHash() As DataTable

    Dim dtSource As DataTable = New DataTable
    dtSource.Columns.Add("Key", System.Type.GetType("System.String"))
    dtSource.Columns.Add("Value", System.Type.GetType("System.String"))
    Dim htCache As Hashtable = CacheManager.GetHash()
    Dim item As DictionaryEntry

    If Not IsNothing(htCache) Then
        For Each item In htCache
            dtSource.Rows.Add(New Object() {item.Key.ToString, item.Value.ToString})
        Next
    End If

    Return dtSource

End Function
wweicker
+1  A: 

Since you potentially want to be removing items from the Cache object, it is not terribly convenient to iterate over it (as an IEnumerable), since this doesn't allow removal during the iteration process. However, given that you cannot access items by index, it is the only solution.

A bit of LINQ can however simplify the problem. Try something like the following:

var cache = HttpContext.Current.Cache;
var itemsToRemove = cache.Where(item => myPredicateHere).ToArray();
foreach (var item in itemsToRemove)
    cache.Remove(itemsToRemove.Key);

Note that each item in the iteration is of type DictionaryEntry.

Noldorin
A: 

Jeff, you should really look up dependencies for your cached items. That's the proper way of doing this. Logically group your cached data (items) and setup dependencies for your groups. This way when you need to expire the entire group you touch such common dependency and they're all gone.

I'm not sure I understand the List of Object part.