1
0

SerialDisposable.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System;
  2. using System.Collections;
  3. namespace UniRx
  4. {
  5. public sealed class SerialDisposable : IDisposable, ICancelable
  6. {
  7. readonly object gate = new object();
  8. IDisposable current;
  9. bool disposed;
  10. public bool IsDisposed { get { lock (gate) { return disposed; } } }
  11. public IDisposable Disposable
  12. {
  13. get
  14. {
  15. return current;
  16. }
  17. set
  18. {
  19. var shouldDispose = false;
  20. var old = default(IDisposable);
  21. lock (gate)
  22. {
  23. shouldDispose = disposed;
  24. if (!shouldDispose)
  25. {
  26. old = current;
  27. current = value;
  28. }
  29. }
  30. if (old != null)
  31. {
  32. old.Dispose();
  33. }
  34. if (shouldDispose && value != null)
  35. {
  36. value.Dispose();
  37. }
  38. }
  39. }
  40. public void Dispose()
  41. {
  42. var old = default(IDisposable);
  43. lock (gate)
  44. {
  45. if (!disposed)
  46. {
  47. disposed = true;
  48. old = current;
  49. current = null;
  50. }
  51. }
  52. if (old != null)
  53. {
  54. old.Dispose();
  55. }
  56. }
  57. }
  58. }