C#Collection其项目到期

ade*_*825 2 c# caching data-structures

我在C#中编写一个控制台应用程序,我希望在预定义的时间内缓存某些项目(假设1小时).我希望已添加到此缓存中的项目在过期后自动删除.我可以使用内置数据结构吗?请记住,这是一个控制台应用程序而非Web应用程序

Jas*_*yne 6

那时你真的需要从缓存中删除它们吗?或者只是未来对该项目的缓存的请求应该在给定时间后返回null?

要做前者,你需要一些定期清除缓存的后台线程.只有在您担心内存消耗或其他问题时才需要这样做.如果您只是希望数据过期,那很容易做到.

创建这样一个课程是微不足道的.

class CachedObject<TValue> 
{ 
 DateTime Date{get;set;}
 TimeSpan Duration{get;set;}
 TValue Cached{get;set;}
}

class Cache : Dictionary<TKey,TValue>
{
  public new TValue this(TKey key)
  {
    get{
    if (ContainsKey(key))
    {
       var val = base.this[key];
       //compare dates
       //if expired, remove from cache, return null
       //else return the cached item.
    }
    }

    set{//create new CachedObject, set date and timespan, set value, add to dictionary}

  }
Run Code Online (Sandbox Code Playgroud)


Arj*_*nbu 6

它已经在BCL了.它不在您期望的位置:您也可以从其他类型的应用程序中使用System.Web.Caching,而不仅仅是在ASP.NET中.

这个搜索谷歌链接到这个的几个资源.

  • 使用MemoryCache而不是http://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache(v=vs.100).aspx请参阅:http://stackoverflow.com/a/793720/303290 tl; dr:"如果在ASP.NET外部使用Cache对象,则不会释放为Cache对象保留的系统内存" (3认同)