Skip to content

Instantly share code, notes, and snippets.

@Dissimilis
Created May 20, 2020 13:05
Show Gist options
  • Save Dissimilis/85a74e0988dddd14eff83e0d67ebf465 to your computer and use it in GitHub Desktop.
Save Dissimilis/85a74e0988dddd14eff83e0d67ebf465 to your computer and use it in GitHub Desktop.
Queue with capacity limit
/// <summary>
/// Queue with limit (last items are removed when limit is reached)
/// </summary>
/// <typeparam name="T"></typeparam>
public class LimitedQueue<T> : ConcurrentQueue<T>
{
private object _syncRoot = new object();
private int? _maxCapacity;
public LimitedQueue() { _maxCapacity = null; }
public LimitedQueue(int capacity) { _maxCapacity = capacity; }
public ICollection<T> All
{
get
{
lock (_syncRoot)
{
return this.ToList();
}
}
}
public void Add(T newElement)
{
if (Count >= _maxCapacity)
{
T o;
TryDequeue(out o);
}
Enqueue(newElement);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment