所以首先我们需要一个优先队列的实现。这是我不久前写的一篇。这可能并不理想;它有一个很小的 API,它可能性能更好,但它是一个足够的起点:
public class PriorityQueue<TPriority, TElement>
{
SortedDictionary<TPriority, Queue<TElement>> dictionary = new SortedDictionary<TPriority, Queue<TElement>>();
public PriorityQueue()
{
}
public Tuple<TPriority, TElement> Peek()
{
var firstPair = dictionary.First();
return Tuple.Create(firstPair.Key, firstPair.Value.First());
}
public TElement Pop()
{
var firstPair = dictionary.First();
TElement output = firstPair.Value.Dequeue();
if (!firstPair.Value.Any())
dictionary.Remove(firstPair.Key);
return output;
}
public void Push(TPriority priority, TElement element)
{
Queue<TElement> queue;
if (dictionary.TryGetValue(priority, out queue))
{
queue.Enqueue(element);
}
else
{
var newQueue = new Queue<TElement>();
newQueue.Enqueue(element);
dictionary.Add(priority, newQueue);
}
}
}
包装时延迟队列很简单:
public class DelayQueue<T>
{
private PriorityQueue<DateTime, T> queue = new PriorityQueue<DateTime, T>();
public void Enqueue(T item, int delay)
{
queue.Push(DateTime.Now.AddMilliseconds(delay), item);
}
public T Dequeue()
{
if (queue.Peek().Item1 > DateTime.Now)
return queue.Pop();
else
return default(T);
}
}