using Sarand.Net.Standard.Base.App; using System; using System.Collections.Generic; using System.Text; namespace Sarand.Net.Standard.Base.Core { //======================================================================= /// /// Dictionary with items queued as if in FIFO list. /// /// Type of key /// Type of value public class SacsQueueDictionary { //------------------------------------------------------------------- // Data memners. private readonly Queue queue = new Queue(); private readonly Dictionary dictionary = new Dictionary(); //------------------------------------------------------------------- // Properties. public int Count { get { lock (dictionary) return queue.Count; } } //------------------------------------------------------------------- /// /// Is the KLey defined in the queue dictionary. /// /// /// True if found, else false. public bool HasValue(K key) { lock (dictionary) { return dictionary.ContainsKey(key); } } //------------------------------------------------------------------- /// /// Retrieve the value determined by the key. /// /// /// Corresponding value if present, else default value. public V GetValue(K key) { V value = default(V); lock (dictionary) { dictionary.TryGetValue(key, out value); } return value; } //------------------------------------------------------------------- public bool SetEntry(K key, V value) { if (key == null || value == null) return false; lock (dictionary) { if (!dictionary.ContainsKey(key)) { // New Key - Add to queue before setting value in dictionary. queue.Enqueue(key); } // Value is set or reset in dictionary whetehr previously exists or not. dictionary[key] = value; } if (SacsSystem.DebugMode) Validate(); return true; } //------------------------------------------------------------------- /// /// Remove the top n entries from the queue dictionary. /// /// /// public List> RemoveTopEntries(int maxEntries) { List> entries = new List>(); lock (dictionary) { while (queue.Count > 0 && entries.Count < maxEntries) { K key = queue.Dequeue(); V value = dictionary[key]; entries.Add(new KeyValuePair(key, value)); dictionary.Remove(key); } } if (SacsSystem.DebugMode) Validate(); return entries; } //------------------------------------------------------------------- // Internal utilities. //------------------------------------------------------------------- private void Validate() { lock (dictionary) { if (queue.Count != dictionary.Count) throw new NotSupportedException("SacsQueueDictionary.Validate Inconsistent entry counts. Quete: " + queue.Count + ". Dictionary: " + dictionary.Count); } } //------------------------------------------------------------------- } //======================================================================= }