I need a requeue at the nth element where n is defined by an ordered key.
ConcurrentQueue<KeyValuePair<string, SomeClass>> queue = new ConcurrentQueue<KeyValuePair<string, SomeClass>>();
queue.RequeueByOrderedKey(key, element)
OR
queue.RequeueN(index, element)
… since it looks necessary to implement this myself, I’m considering something based on public
class Class1 : KeyedCollection<K,V>{}
it'd be nice to have Class1 : OrderedKeyedCollection<K,V>{}
Here’s some code that I did. I’ll put it here for comment, and then probably move it to be an answer. Probably haven’t handled the concurrency stuff properly yet.
public class QueueExt<TK, TV> : SortedList<TK, TV> {
#region Constructors
public QueueExt(Func<TV, TK> getKey = null) {
GetKey = getKey;
}
private Func<TV, TK> GetKey = null;
public QueueExt(int capacity, Func<TV, TK> getKey = null)
: base(capacity) {
GetKey = getKey;
}
public QueueExt(IComparer<TK> comparer, Func<TV, TK> getKey = null)
: base(comparer) {
GetKey = getKey;
}
public QueueExt(int capacity, IComparer<TK> comparer, Func<TV, TK> getKey = null)
: base(capacity, comparer) {
GetKey = getKey;
}
public QueueExt(IDictionary<TK, TV> dictionary, Func<TV, TK> getKey = null)
: base(dictionary) {
GetKey = getKey;
}
public QueueExt(IDictionary<TK, TV> dictionary, IComparer<TK> comparer, Func<TV, TK> getKey = null)
: base(dictionary, comparer) {
GetKey = getKey;
}
#endregion
public TV Dequeue() {
lock (this) {
var first = this.ElementAt(0).Value;
this.RemoveAt(0);
return first;
}
}
public void Requeue() {
if (GetKey == null)
throw new ArgumentNullException("Key getter lamda must not be null");
lock (this) {
var key = this.ElementAt(0).Key;
var actualkey = GetKey(this.ElementAt(0).Value);
if (!actualkey.Equals(key)) {
this.Enqueue(this.Dequeue());
}
}
}
public void Enqueue(TK key, TV item) {
this.Add(key, item);
}
public void Enqueue(TV item) {
if (GetKey == null)
throw new ArgumentNullException("Key getter lamda must not be null");
var key = GetKey(item);
this.Add(key, item);
}
public TV Peek() {
return this.ElementAt(0).Value;
}
}
You can do this with BlockingCollection. You create your indexable queue and make it implement IProducerConsumerCollection. I show how to use
BlockingCollectionthis way in my article Customizing Blocking Collection. I use a stack in the article, but you could easily enough replace the stack with your indexable queue.An alternative might be a concurrent priority queue. You can build a simple one with a heap and a lock. See my article A Generic Binary Heap. You’ll need to add the synchronization.