SerialDisposableValue.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Threading;
  5. namespace System.Reactive.Disposables
  6. {
  7. /// <summary>
  8. /// Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource.
  9. /// </summary>
  10. internal struct SerialDisposableValue : ICancelable
  11. {
  12. private IDisposable? _current;
  13. /// <summary>
  14. /// Gets a value that indicates whether the object is disposed.
  15. /// </summary>
  16. public bool IsDisposed =>
  17. // We use a sentinel value to indicate we've been disposed. This sentinel never leaks
  18. // to the outside world (see the Disposable property getter), so no-one can ever assign
  19. // this value to us manually.
  20. Volatile.Read(ref _current) == BooleanDisposable.True;
  21. /// <summary>
  22. /// Gets or sets the underlying disposable.
  23. /// </summary>
  24. /// <remarks>If the SerialDisposable has already been disposed, assignment to this property causes immediate disposal of the given disposable object. Assigning this property disposes the previous disposable object.</remarks>
  25. public IDisposable? Disposable
  26. {
  27. get => Disposables.Disposable.GetValue(ref _current);
  28. set => Disposables.Disposable.TrySetSerial(ref _current, value);
  29. }
  30. /// <summary>
  31. /// Disposes the underlying disposable as well as all future replacements.
  32. /// </summary>
  33. public void Dispose()
  34. {
  35. Disposables.Disposable.Dispose(ref _current);
  36. }
  37. }
  38. }