I have a Queue<T> object that I have initialised to a capacity of 2, but obviously that is just the capacity and it keeps expanding as I add items. Is there already an object that automatically dequeues an item when the limit is reached, or is the best solution to create my own inherited class?
I've knocked up a basic version of what I'm looking for, it's not perfect but it'll do the job until something better comes along.
I would recommend that you pull up the C5 Library. Unlike SCG (System.Collections.Generic), C5 is programmed to interface and designed to be subclassed. Most public methods are virtual and none of the classes are sealed. This way, you won't have to use that icky "new" keyword which wouldn't trigger if your
LimitedQueue<T>
were cast to aSCG.Queue<T>
. With C5 and using close to the same code as you had before, you would derive from theCircularQueue<T>
. TheCircularQueue<T>
actually implements both a stack and a queue, so you can get both options with a limit nearly for free. I've rewritten it below with some 3.5 constructs:I think that this code should do exactly what you were looking for.
You should create your own class, a ringbuffer would probably fit your needs.
The data structures in .NET that allows you to specify capacity, except for array, uses this to build the internal data structure used to hold the internal data.
For instance, for a list, capacity is used to size an internal array. When you start adding elements to the list, it'll start filling this array from index 0 and up, and when it reaches your capacity, it increases the capacity to a new higher capacity, and continues filling it up.
Why wouldn't you just use an array with a size of 2? A Queue is supposed to be able to dynamically grow and shrink.
Or create a wrapper class around an instance of
Queue<T>
instance and each time one enqueues a<T>
object, check the size of the queue. If larger than 2, dequeue the first item.Well I hope this class will helps You:
Internally the Circular FIFO Buffer use a Queue<T> with the specified size. Once the size of the buffer is reached, it will replaces older items with new ones.
NOTE: You can't remove items randomly. I set the method Remove(T item) to return false. if You want You can modify to remove items randomly
Concurrent Solution
Note: Since
Enqueue
controls the addition of elements, and does so one at a time, there is no need to execute awhile
forTryDequeue
.If it's of any use to anyone, I made a
LimitedStack<T>
.It removes the oldest item (bottom of stack) when it gets too big.
(This question was the top Google result for "C# limit stack size")