我正在尝试使用SortedDictionary实现优先级队列机制,并希望得到关于我的当前实现的建议。
我的实现如下:
public class PriorityQueue
{
private Object lockObj;
private SortedDictionary<PQMsgPriority, Queue<PQMessage>> messageDictionary;
public PriorityQueue()
{
lockObj = new object();
messageDictionary = new SortedDictionary<PQMsgPriority, Queue<PQMessage>>();
}
public void Enqueue(PQMessage item)
{
lock (lockObj)
{
if(item != null && item.MsgPriority == PQMsgPriority.None)
{
if (messageDictionary.ContainsKey(item.MsgPriority))
{
Queue<PQMessage> dataList = messageDictionary[item.MsgPriority];
dataList.Enqueue(item);
messageDictionary[item.MsgPriority] = dataList;
}
else
{
Queue<PQMessage> dataList = new Queue<PQMessage>();
dataList.Enqueue(item);
messageDictionary.Add(item.MsgPriority, dataList);
}
}
}
}
public PQMessage Dequeue()
{
lock (lockObj)
{
PQMessage messageData = null;
PQMsgPriority deleteKey = PQMsgPriority.None;
//If no data available, throw an exception
if (messageDictionary.Count == 0)
throw new InvalidOperationException();
foreach (KeyValuePair<PQMsgPriority, Queue<PQMessage>> item in messageDictionary)
{
Queue<PQMessage> dataList = item.Value;
messageData = dataList.Dequeue();
messageDictionary[item.Key] = dataList;
//If there is no more elements remaining in the list, set a flag (deleteKey) for deleting the key
if (dataList.Count == 0)
deleteKey = item.Key;
break;
}
//If the deleteKey flag is set, delete the key from the dictionary
if (deleteKey != PQMsgPriority.None)
messageDictionary.Remove(deleteKey);
return messageData;
}
}
public int Count()
{
lock (lockObj)
{
return messageDictionary.Count;
}
}
public PQMessage Peek()
{
lock (lockObj)
{
PQMessage messageData = null;
//If no data available, throw an exception
if (messageDictionary.Count == 0)
throw new InvalidOperationException();
foreach (KeyValuePair<PQMsgPriority, Queue<PQMessage>> item in messageDictionary)
{
Queue<PQMessage> dataList = item.Value;
messageData = dataList.Peek();
break;
}
return messageData;
}
}
}
public enum PQMsgPriority
{
High = 0,
Medium = 1,
Low = 2,
None = 3
}
public class PQMessage
{
private PQMsgPriority msgPriority;
private Object message;
#region Properties
public PQMsgPriority MsgPriority
{
get { return msgPriority; }
set { msgPriority = value; }
}
public Object Message
{
get { return message; }
set { message = value; }
}
#endregion
public PQMessage(PQMsgPriority msgPriority, Object message)
{
this.msgPriority = msgPriority;
this.message = message;
}
}
如果有其他实现优先队列的方法,请指点我正确的方向。