Список Объекта в httpcontext.current.cache

Я все еще делаю это старый путь путем определения макроса (XTRACE, ниже), который коррелирует или к не или к вызов функции со списком аргумента переменной. Внутренне, назовите vsnprintf, таким образом, можно сохранить printf синтаксис:

#include <stdio.h>

void XTrace0(LPCTSTR lpszText)
{
   ::OutputDebugString(lpszText);
}

void XTrace(LPCTSTR lpszFormat, ...)
{
    va_list args;
    va_start(args, lpszFormat);
    int nBuf;
    TCHAR szBuffer[512]; // get rid of this hard-coded buffer
    nBuf = _vsnprintf(szBuffer, 511, lpszFormat, args);
    ::OutputDebugString(szBuffer);
    va_end(args);
}

Тогда типичный переключатель #ifdef:

#ifdef _DEBUG
#define XTRACE XTrace
#else
#define XTRACE
#endif

Хорошо, который может быть очищен вполне немного, но это - основная идея.

6
задан John Saunders 19 October 2011 в 15:08
поделиться

5 ответов

Yes, you can either index based on the cache key, or 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
5
ответ дан 8 December 2019 в 02:27
поделиться

Вот функция VB для перебора кэша и возврата представления DataTable.

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
3
ответ дан 8 December 2019 в 02:27
поделиться

Поскольку вы потенциально хотите удалить элементы из объекта Cache , не очень удобно перебирать его (как IEnumerable ), поскольку это не позволяет удалять во время итерационного процесса. Однако, учитывая, что вы не можете получить доступ к элементам по индексу, это единственное решение.

Однако немного LINQ может упростить проблему. Попробуйте что-нибудь вроде следующего:

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

Обратите внимание, что каждый элемент в итерации имеет тип DictionaryEntry .

1
ответ дан 8 December 2019 в 02:27
поделиться

You can enumerate through the objects:

 System.Web.HttpContext.Current.Cache.GetEnumerator()
6
ответ дан 8 December 2019 в 02:27
поделиться

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.

1
ответ дан 8 December 2019 в 02:27
поделиться
Другие вопросы по тегам:

Похожие вопросы: