SafeDictionary.cs 844 B

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