C#死亡延迟队列DelayQueue
public class DelayQueue<T>
{
private List<DelayQueueItem<T>> items = new List<DelayQueueItem<T>>();
public void Enqueue(T item)
{
Enqueue(item, TimeSpan.Zero);
}
public void Enqueue(T item, TimeSpan delay)
{
items.Add(new DelayQueueItem<T>()
{
Value = item,
ReadyTime = DateTime.Now.Add(delay)
});
}
public T Dequeue()
{
DateTime now = DateTime.Now;
var item = items.FirstOrDefault(i => i.ReadyTime <= now);
if (item != null)
{
items.Remove(item);
return item.Value;
}
return default(T);
}
private class DelayQueueItem<T>
{
public T Value { get; set; }
public DateTime ReadyTime { get; set; }
}
}
update
public T Dequeue()
{
return Dequeue(TimeSpan.Zero);
}
public T Dequeue(TimeSpan timeout)
{
DateTime startTime = DateTime.Now;
do
{
DateTime now = DateTime.Now;
var item = items.FirstOrDefault(i => i.ReadyTime <= now);
if (item == null)
continue;
items.Remove(item);
return item.Value;
}
while (DateTime.Now - startTime < timeout);
return default(T);
}
用法:
queue.Enqueue("world", new TimeSpan(0, 0, 1));
queue.Enqueue("hello");
queue.Enqueue(",");
TimeSpan timeout = new TimeSpan(0, 0, 2);
Console.WriteLine(queue.Dequeue());
Console.WriteLine(queue.Dequeue(timeout));
Console.WriteLine(queue.Dequeue(timeout));