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


- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- WebMatrix WebSecurity PasswordSalt 2022-01-01