SafeDictionary.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using System;
  2. using System.Collections.Generic;
  3. namespace FastJSON
  4. {
  5. public sealed class SafeDictionary<TKey, TValue>
  6. {
  7. private readonly object _Padlock = new object();
  8. private readonly Dictionary<TKey, TValue> _Dictionary;
  9. public SafeDictionary(int capacity)
  10. {
  11. _Dictionary = new Dictionary<TKey, TValue>(capacity);
  12. }
  13. public SafeDictionary()
  14. {
  15. _Dictionary = new Dictionary<TKey, TValue>();
  16. }
  17. public bool TryGetValue(TKey key, out TValue value)
  18. {
  19. lock (_Padlock)
  20. return _Dictionary.TryGetValue(key, out value);
  21. }
  22. public int Count { get { lock (_Padlock) return _Dictionary.Count; } }
  23. public TValue this[TKey key]
  24. {
  25. get
  26. {
  27. lock (_Padlock)
  28. return _Dictionary[key];
  29. }
  30. set
  31. {
  32. lock (_Padlock)
  33. _Dictionary[key] = value;
  34. }
  35. }
  36. public void Add(TKey key, TValue value)
  37. {
  38. lock (_Padlock)
  39. {
  40. if (_Dictionary.ContainsKey(key) == false)
  41. _Dictionary.Add(key, value);
  42. }
  43. }
  44. }
  45. }