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

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

问题描述

我将 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 个浏览的 Url.我想要一个队列,当容量已满(历史上的 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 ?

推荐答案

我会写一个包装类,它在 Enqueue 上会检查 Count,然后当计数超过限制时 Dequeue.

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>();
     private object lockObject = new object();

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

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

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