SafeDictionary.cs 1.2 KB

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