キャッシュ内のすべてのオブジェクトを調べる方法はありますか? オブジェクトを動的に作成していますが、定期的にリストを調べて、使用しなくなったオブジェクトを削除する必要があります。
7 に答える
var keysToClear = (from System.Collections.DictionaryEntry dict in HttpContext.Cache
let key = dict.Key.ToString()
where key.StartsWith("Something_")
select key).ToList();
foreach (var key in keysToClear)
{
HttpContext.Cache.Remove(key);
}
オブジェクトを列挙できます。
System.Web.HttpContext.Current.Cache.GetEnumerator()
はい、キャッシュキーに基づいてインデックスを作成するか、コンテンツを反復処理できます。
For Each c In Cache
' Do something with c
Next
' Pardon my VB syntax if it's wrong
以下は、キャッシュを反復処理して DataTable 表現を返す VB 関数です。
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
これは少し遅いかもしれませんが、次のコードを使用して、すべてのキャッシュ アイテムを簡単に繰り返し処理し、名前に特定の文字列を含むキャッシュ アイテムを削除するためのカスタム ロジックを実行しました。
VB.Net と C# の両方のバージョンのコードを提供しました。
VB.Net バージョン
Dim cacheItemsToRemove As New List(Of String)()
Dim key As String = Nothing
'loop through all cache items
For Each c As DictionaryEntry In System.Web.HttpContext.Current.Cache
key = DirectCast(c.Key, String)
If key.Contains("prg") Then
cacheItemsToRemove.Add(key)
End If
Next
'remove the selected cache items
For Each k As var In cacheItemsToRemove
System.Web.HttpContext.Current.Cache.Remove(k)
Next
C# バージョン
List<string> cacheItemsToRemove = new List<string>();
string key = null;
//loop through all cache items
foreach (DictionaryEntry c in System.Web.HttpContext.Current.Cache)
{
key = (string)c.Key;
if (key.Contains("prg"))
{
cacheItemsToRemove.Add(key);
}
}
//remove the selected cache items
foreach (var k in cacheItemsToRemove)
{
System.Web.HttpContext.Current.Cache.Remove(k);
}
ジェフ、キャッシュされたアイテムの依存関係を本当に調べるべきです。それがこれを行う適切な方法です。キャッシュされたデータ (アイテム) を論理的にグループ化し、グループの依存関係をセットアップします。このようにして、グループ全体を期限切れにする必要がある場合、そのような共通の依存関係に触れると、それらはすべてなくなります。
オブジェクトのリストの部分を理解しているかどうかわかりません。
オブジェクトからアイテムを削除したい可能性があるため、反復プロセス中に削除できないため、Cache
( として) 反復処理するのはあまり便利ではありません。IEnumerable
ただし、インデックスでアイテムにアクセスできないことを考えると、これが唯一の解決策です。
ただし、LINQ を少し使用すると、問題を単純化できます。次のようなことを試してください。
var cache = HttpContext.Current.Cache;
var itemsToRemove = cache.Where(item => myPredicateHere).ToArray();
foreach (var item in itemsToRemove)
cache.Remove(itemsToRemove.Key);
item
反復内のそれぞれのタイプは であることに注意してくださいDictionaryEntry
。