SingleAssignmentDisposable.cs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. #nullable disable
  5. namespace System.Reactive.Disposables
  6. {
  7. /// <summary>
  8. /// Represents a disposable resource which only allows a single assignment of its underlying disposable resource.
  9. /// If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an <see cref="InvalidOperationException"/>.
  10. /// </summary>
  11. public sealed class SingleAssignmentDisposable : ICancelable
  12. {
  13. private IDisposable _current;
  14. /// <summary>
  15. /// Initializes a new instance of the <see cref="SingleAssignmentDisposable"/> class.
  16. /// </summary>
  17. public SingleAssignmentDisposable()
  18. {
  19. }
  20. /// <summary>
  21. /// Gets a value that indicates whether the object is disposed.
  22. /// </summary>
  23. public bool IsDisposed => Disposables.Disposable.GetIsDisposed(ref _current);
  24. /// <summary>
  25. /// Gets or sets the underlying disposable. After disposal, the result of getting this property is undefined.
  26. /// </summary>
  27. /// <exception cref="InvalidOperationException">Thrown if the <see cref="SingleAssignmentDisposable"/> has already been assigned to.</exception>
  28. public IDisposable Disposable
  29. {
  30. get => Disposables.Disposable.GetValueOrDefault(ref _current);
  31. set => Disposables.Disposable.SetSingle(ref _current, value);
  32. }
  33. /// <summary>
  34. /// Disposes the underlying disposable.
  35. /// </summary>
  36. public void Dispose()
  37. {
  38. Disposables.Disposable.TryDispose(ref _current);
  39. }
  40. }
  41. }