2
0

MultipleAssignmentDisposable.cs 1.5 KB

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