SingleAssignmentDisposableValue.cs 1.8 KB

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