DisposableDictionary.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace Masuit.Tools.Systems;
  5. /// <summary>
  6. /// 值可被Dispose的字典类型
  7. /// </summary>
  8. /// <typeparam name="TKey"></typeparam>
  9. /// <typeparam name="TValue"></typeparam>
  10. public class DisposableDictionary<TKey, TValue> : NullableDictionary<TKey, TValue>, IDisposable where TValue : IDisposable
  11. {
  12. private bool _isDisposed;
  13. /// <summary>
  14. /// 终结器
  15. /// </summary>
  16. ~DisposableDictionary()
  17. {
  18. Dispose(false);
  19. }
  20. /// <summary>
  21. ///
  22. /// </summary>
  23. public void Dispose()
  24. {
  25. if (_isDisposed)
  26. {
  27. return;
  28. }
  29. Dispose(true);
  30. _isDisposed = true;
  31. GC.SuppressFinalize(this);
  32. }
  33. public DisposableDictionary()
  34. {
  35. }
  36. public DisposableDictionary(TValue fallbackValue) : base()
  37. {
  38. FallbackValue = fallbackValue;
  39. }
  40. public DisposableDictionary(int capacity) : base(capacity)
  41. {
  42. }
  43. public DisposableDictionary(IDictionary<NullObject<TKey>, TValue> dictionary) : base(dictionary)
  44. {
  45. }
  46. /// <summary>
  47. /// 释放
  48. /// </summary>
  49. /// <param name="disposing"></param>
  50. public void Dispose(bool disposing)
  51. {
  52. foreach (var s in Values.Where(v => v != null))
  53. {
  54. s.Dispose();
  55. }
  56. }
  57. }