Asp.net

ASP.net 記憶體絕對過期不起作用

  • December 23, 2014

我在 HttpContext.Cache 中儲存一個整數值,從現在開始的絕對過期時間為 5 分鐘。但是,在等待 6 分鐘(或更長時間)後,整數值仍在記憶體中(即,即使絕對過期已過,它也不會被刪除)。這是我正在使用的程式碼:

public void UpdateCountFor(string remoteIp)
{
   // only returns true the first time its run
   // after that the value is still in the Cache
   // even after the absolute expiration has passed
   // so after that this keeps returning false
   if (HttpContext.Current.Cache[remoteIp] == null)
   {
       // nothing for this ip in the cache so add the ip as a key with a value of 1
       var expireDate = DateTime.Now.AddMinutes(5);
       // I also tried:
       // var expireDate = DateTime.UtcNow.AddMinutes(5); 
       // and that did not work either.
       HttpContext.Current.Cache.Insert(remoteIp, 1, null, expireDate, Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
   }
   else
   {
       // increment the existing value
       HttpContext.Current.Cache[remoteIp] = ((int)HttpContext.Current.Cache[remoteIp]) + 1;
   }
}

我第一次執行 UpdateCountFor(“127.0.0.1”) 時,它會將 1 插入到記憶體中,鍵為“127.0.0.1”,並且從現在起絕對過期 5 分鐘,正如預期的那樣。然後每次後續執行都會增加記憶體中的值。但是,在等待 10 分鐘後,它會繼續增加 Cache 中的值。該值永不過期,也永遠不會從記憶體中刪除。這是為什麼?

據我了解,絕對到期時間意味著該項目將在那個時候被刪除。難道我做錯了什麼?我是不是誤會了什麼?

我預計該值會在 5 分鐘後從記憶體中刪除,但是它會一直保留在那裡,直到我重建項目。

這一切都在我本地機器上的 .NET 4.0 上執行。

事實證明,這一行:

HttpContext.Current.Cache[remoteIp] = ((int)HttpContext.Current.Cache[remoteIp]) + 1;

刪除先前的值並重新插入沒有絕對或滑動到期時間的值。為了解決這個問題,我必須創建一個輔助類並像這樣使用它:

public class IncrementingCacheCounter
{
   public int Count;
   public DateTime ExpireDate;
}

public void UpdateCountFor(string remoteIp)
{
   IncrementingCacheCounter counter = null;
   if (HttpContext.Current.Cache[remoteIp] == null)
   {
       var expireDate = DateTime.Now.AddMinutes(5);
       counter = new IncrementingCacheCounter { Count = 1, ExpireDate = expireDate };
   }
   else
   {
       counter = (IncrementingCacheCounter)HttpContext.Current.Cache[remoteIp];
       counter.Count++;
   }
   HttpContext.Current.Cache.Insert(remoteIp, counter, null, counter.ExpireDate, Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
}

這將解決這個問題,讓計數器在絕對時間正確過期,同時仍然啟用對其的更新。

引用自:https://stackoverflow.com/questions/5902255