2012-06-21 5 views

답변

5

당신이 캐시에 항목을 추가하고, 당신은 세계 키로 CacheDependency로 추가해야합니다. 이렇게하면 주어진 시간이 지나면 항목이 만료 될뿐만 아니라이 키에 연결된 모든 항목이 지워집니다.

/// <summary> 
/// Caching provider 
/// </summary> 
public static class CacheProvider 
{ 
    const string CacheDependencyKey = "1FADE275-2C84-4a9b-B3E1-68ABB15E53C8"; 
    static readonly object SyncRoot = new object(); 

    /// <summary> 
    /// Gets an item from cache. If the item does not exist, one will be 
    /// created and added to the cache. 
    /// </summary> 
    /// <param name="key">Caching key</param> 
    /// <param name="valueFactory">Function to create the item of it does not exist in the cache.</param> 
    /// <param name="expiresAfter">Time after the item wille be removed from cache.</param> 
    public static TValue GetOrAdd<TValue>(string key, Func<TValue> valueFactory, TimeSpan expiresAfter) 
    { 
     object itemFromCache = HttpRuntime.Cache.Get(key); 
     if (itemFromCache == null) 
     { 
      lock (SyncRoot) 
      { 
       itemFromCache = HttpRuntime.Cache.Get(key); 
       if (itemFromCache == null) 
       { 
        TValue value = valueFactory(); 
        if (value != null) 
        { 
         if (HttpRuntime.Cache[CacheDependencyKey] == null) 
          HttpRuntime.Cache[CacheDependencyKey] = string.Empty; 

         HttpRuntime.Cache.Add(key, value, new CacheDependency(null, new string[] { CacheDependencyKey }), DateTime.Now.Add(expiresAfter), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null); 
        } 
        return value; 
       } 
      } 
     } 
     return (TValue)itemFromCache; 
    } 

    /// <summary> 
    /// Invalidate all the items from the cache. 
    /// </summary> 
    public static void InvalidateCache() 
    { 
     HttpRuntime.Cache.Remove(CacheDependencyKey); 
    } 
} 
+0

는 CacheDependency 내 경우 Cache.Insert를 사용하여, 나를 위해 그것을 해결 : 여기

는 모든 항목을 삭제하는 방법의 예 구현 (CacheProvider.cs)입니다 –

2
public void Clear() 
{ 
    var itemsToRemove = new List<string>(); 

    var enumerator = HttpContext.Current.Cache.GetEnumerator(); 
    while (enumerator.MoveNext()) 
    { 
     itemsToRemove.Add(enumerator.Key.ToString()); 
    } 

    foreach (string itemToRemove in itemsToRemove) 
    { 
     HttpContext.Current.Cache.Remove(itemToRemove); 
    } 
} 
관련 문제