具有超时/过期能力的列表

Nim*_*oud 19 c# list

我需要一个这样的函数:

AddToList(txtName, timeExpire);
Run Code Online (Sandbox Code Playgroud)

它看起来像是自描述的,该项目将自动过期并从列表中删除.

我无法想象如何做到这一点.任何人都可以给我一个线索吗?

小智 24

如果您的目标是.NET 4或更高版本,请使用MemoryCache(或从ObjectCache派生自定义实现).

回到4之前,如果你想在你的应用程序中使用缓存,你可以简单地抓住System.Web.Cache并在任何.NET应用程序中使用它.它对任何"web"代码都没有任何实际依赖关系,但确实需要您引用System.Web.dll.这似乎很奇怪(比如从C#应用程序引用Microsoft.VisualBasic.dll),但实际上并没有对您的应用程序造成负面影响.

随着客户端配置文件的出现,打破以桌面为中心的代码和以服务器为中心的代码之间的依赖关系变得非常重要.因此引入了ObjectCache,以便桌面应用程序(不确定silverlight,wp7)开发人员可以打破这种依赖关系,并能够只针对客户端配置文件.


Ada*_*ley 13

只是一个快速的例子,答案将给出

添加对System.Runtime.Caching的引用

 MemoryCache cache = new MemoryCache("CacheName");

 cache.Add(key, value, new CacheItemPolicy() 
                           { AbsoluteExpiration = DateTime.UtcNow.AddSeconds(20) });
Run Code Online (Sandbox Code Playgroud)

然后,您可以通过访问来检查缓存中是否仍有某些内容

 if (cache.Contains(key))
Run Code Online (Sandbox Code Playgroud)

如果您希望缓存具有较低的时间限制,那么您需要通过一个不错的小黑客来更改缓存的刷新时间.

MemoryCache AbsoluteExpiration表现奇怪

  • @Zapnologica MemoryCache完全是线程安全的,请看这个答案:http://stackoverflow.com/a/6738179/606554 (2认同)

Har*_*san 8

你也可以试试这样的东西.

创建自定义类

 public class Custom
    {
        string item; //will hold the item
        Timer timer; //will hanlde the expiry
        List<Custom> refofMainList; //will be used to remove the item once it is expired

        public Custom(string yourItem, int milisec, List<Custom> refOfList)
        {
            refofMainList = refOfList;
            item = yourItem;
            timer = new Timer (milisec);
            timer.Elapsed += new ElapsedEventHandler(Elapsed_Event);
            timer.Start();
        }

        private void Elapsed_Event(object sender, ElapsedEventArgs e)
        {
            timer.Elapsed -= new ElapsedEventHandler(Elapsed_Event);
            refofMainList.Remove(this);

        }
    }
Run Code Online (Sandbox Code Playgroud)

现在您可以创建List<Custom>和使用它.一旦指定的时间结束,它的项目将被删除.

  • 这种方法将如何在IIS中运行的asp.net api中运行.我相信在iis中运行定时器有并发症吗? (2认同)
  • 尽管答案没有直接说明,但`ElapsedEventHandler` 表明这是使用`System.Timers.Timer` 在不同线程上运行回调。对于这个答案来说,这是一个大问题,因为`List&lt;T&gt;` 不是线程安全的。 (2认同)