3

Is there a Queue type collection in .NET at allows elements to be pushed out of the queue when the capacity of the queue is reached?

Ben Waine
  • 1,600
  • 3
  • 19
  • 34

2 Answers2

3

Pretty trivial to do yourself by just calling Dequeue when the Count goes up beyond your limit after calling Add(). An extension method jumps to mind.

Hans Passant
  • 873,011
  • 131
  • 1,552
  • 2,371
2

I'd suggest creating a new class, rather than subclassing queue, since the limited-length queue class should not be passable to code which might call the old enqueue method. There are a number of logical things that a queue might do if a push occurs when full:

  1. Throw an exception on push
  2. Wait for an item to be read
  3. Drop oldest item
  4. Drop newest item
  5. Invalidate queue so it will throw an exception on the next read, but return from the push; further pushes will become no-ops.

It may be good to create an inheritable base class, and then create derived classes which implement particular behaviors. That way methods which care about the problem scenario could demand a class which promises handles it correctly. Note that the last scenario may seem strange, but there are times it'd be appropriate, e.g. an event handler putting data into a queue for some other task to process. If the queue is large enough that it shouldn't ever overflow, but the reader task gets blocked, it may be be undesirable to have such blockage percolate back to the event sender.

supercat
  • 69,493
  • 7
  • 143
  • 184