using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace POSV.Utils { public interface IKV { bool TryGetValue(T key , out V val); int Count(); IEnumerator> GetEnumerator(); void Add(T key , V value); T[] Keys(); bool Remove(T key); void Clear(); V GetValue(T key); // safesortedlist only //V GetValue(int index); //T GetKey(int index); } public class SafeDictionary : IKV { private readonly object _Padlock = new object(); private readonly Dictionary _Dictionary; public SafeDictionary(int capacity) { _Dictionary = new Dictionary(capacity); } public SafeDictionary() { _Dictionary = new Dictionary(); } public bool TryGetValue(TKey key , out TValue value) { lock (_Padlock) return _Dictionary.TryGetValue(key , out value); } public TValue this[TKey key] { get { lock (_Padlock) return _Dictionary[key]; } set { lock (_Padlock) _Dictionary[key] = value; } } public int Count() { lock (_Padlock) return _Dictionary.Count; } public IEnumerator> GetEnumerator() { return ((ICollection>)_Dictionary).GetEnumerator(); } public void Add(TKey key , TValue value) { lock (_Padlock) { if (_Dictionary.ContainsKey(key) == false) _Dictionary.Add(key , value); else _Dictionary[key] = value; } } public TKey[] Keys() { lock (_Padlock) { TKey[] keys = new TKey[_Dictionary.Keys.Count]; _Dictionary.Keys.CopyTo(keys , 0); return keys; } } public bool Remove(TKey key) { if (key == null) return true; lock (_Padlock) { return _Dictionary.Remove(key); } } public void Clear() { lock (_Padlock) _Dictionary.Clear(); } public TValue GetValue(TKey key) { lock (_Padlock) return _Dictionary[key]; } } public class SafeSortedList : IKV { private object _padlock = new object(); SortedList _list = new SortedList(); public int Count() { lock (_padlock) return _list.Count; } public void Add(T key , V val) { lock (_padlock) { if (_list.ContainsKey(key) == false) _list.Add(key , val); else _list[key] = val; } } public bool Remove(T key) { if (key == null) return true; lock (_padlock) return _list.Remove(key); } public T GetKey(int index) { lock (_padlock) return _list.Keys[index]; } public V GetValue(int index) { lock (_padlock) return _list.Values[index]; } public T[] Keys() { lock (_padlock) { T[] keys = new T[_list.Keys.Count]; _list.Keys.CopyTo(keys , 0); return keys; } } public IEnumerator> GetEnumerator() { return ((ICollection>)_list).GetEnumerator(); } public bool TryGetValue(T key , out V value) { lock (_padlock) return _list.TryGetValue(key , out value); } public void Clear() { lock (_padlock) _list.Clear(); } public V GetValue(T key) { lock (_padlock) return _list[key]; } } }