Fixed size queue which automatically dequeues old values upon new 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 个浏览的 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)) ;
}
}
}
这篇关于固定大小的队列,在新入队时自动将旧值出列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:固定大小的队列,在新入队时自动将旧值出列


基础教程推荐
- 如果条件可以为空 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 将数据集转换为列表 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 获取C#保存对话框的文件路径 2022-01-01