固定大小的队列在新enques自动离队旧值 [英] Fixed size queue which automatically dequeues old values upon new enques

查看:178
本文介绍了固定大小的队列在新enques自动离队旧值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用 ConcurrentQueue 为此目的持有传递给它(那种历史)。最后N个对象共享数据结构

I'm using ConcurrentQueue for a shared data structure which purpose is holding the last N objects passed to it (kind of history).

假设我们有一个浏览器,我们希望有最后100浏览网址。我想一个队列自动降(离队)在新条目插入(排队)当容量已满(100个地址在历史上)最老的(第一个)项目。

Assume we have a browser and we want to have the last 100 browsed Urls. I want a queue which automatically drop (dequeue) the oldest (first) entry upon new entry insertion (enqueue) when the capacity gets full (100 addresses in history).

我如何可以完成,使用 System.Collections中

How can I accomplish that using System.Collections ?

推荐答案

我会写一个包装类,当计数超过限制的排队将检查Count,然后出队。

I would write a wrapper class that on Enqueue would check the Count and then Dequeue when the count exceeds the limit.

 public class FixedSizedQueue<T>
 {
     ConcurrentQueue<T> q = new ConcurrentQueue<T>();

     public int Limit { get; set; }
     public void Enqueue(T obj)
     {
        q.Enqueue(obj);
        lock (this)
        {
           T overflow;
           while (q.Count > Limit && q.TryDequeue(out overflow)) ;
        }
     }
 }

这篇关于固定大小的队列在新enques自动离队旧值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆