ThreadSafeDictionary.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Runtime.InteropServices;
  4. using System.Linq;
  5. namespace Helper
  6. {
  7. public class ThreadSafeDictionary<TKey, TValue>
  8. {
  9. protected readonly Dictionary<TKey, TValue> _impl = new Dictionary<TKey, TValue>();
  10. public TValue this[TKey key]
  11. {
  12. get
  13. {
  14. lock (_impl)
  15. {
  16. return _impl[key];
  17. }
  18. }
  19. set
  20. {
  21. lock (_impl)
  22. {
  23. _impl[key] = value;
  24. }
  25. }
  26. }
  27. public void Add(TKey key, TValue value)
  28. {
  29. lock (_impl)
  30. {
  31. _impl.Add(key, value);
  32. }
  33. }
  34. public bool TryGetValue(TKey key, out TValue value)
  35. {
  36. lock (_impl)
  37. {
  38. return _impl.TryGetValue(key, out value);
  39. }
  40. }
  41. public bool Remove(TKey key)
  42. {
  43. lock (_impl)
  44. {
  45. return _impl.Remove(key);
  46. }
  47. }
  48. public void Clear()
  49. {
  50. lock (_impl)
  51. {
  52. _impl.Clear();
  53. }
  54. }
  55. }
  56. }