How would I implement a QueueDictionary, a combination of Queue and Dictionary in C#?

前端 未结 3 801
无人及你
无人及你 2021-01-18 15:00

Basically the data structure I want would mirror a MSMQ but would be in memory, because it is being used in the one process. By mirroring MSMQ I mean you would enqueue objec

3条回答
  •  萌比男神i
    2021-01-18 15:41

    Rather than using a Queue internally, you could use a LinkedList. Then in the Dictionary you can store the Key and the LinkedListNode. Then when you remove the item from the Dictionary, you can unlink the LinkedListNode from the linked list. Of course you loose the locality of the Queue, but gain the performance of the random access.

    Here is a quick and dirty example, not tested so excuse any errors and no error checking. For example you should check if the queue is empty, make sure an item with the same key is not already in the dictionary etc.

    public class QueueDictionary
    {
      private readonly LinkedList> _queue =
        new LinkedList>();
    
      private readonly Dictionary>> 
        _dictionary = new Dictionary>>();
    
      private readonly object _syncRoot = new object();
    
      public TValue Dequeue()
      {
        lock (_syncRoot)
        {
          Tuple item = _queue.First();
          _queue.RemoveFirst();
          _dictionary.Remove(item.Item1);
          return item.Item2;
        }
      }
    
      public TValue Dequeue(TKey key)
      {
        lock (_syncRoot)
        {
          LinkedListNode> node = _dictionary[key];
          _dictionary.Remove(key);
          _queue.Remove(node);
          return node.Value.Item2;
        }
      }
    
      public void Enqueue(TKey key, TValue value)
      {
        lock (_syncRoot)
        {
          LinkedListNode> node = 
            _queue.AddLast(new Tuple(key, value));
          _dictionary.Add(key, node);
        }
      }
    }
    

提交回复
热议问题