ScheduledDisposable.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. using System.Reactive.Concurrency;
  6. namespace System.Reactive.Disposables
  7. {
  8. /// <summary>
  9. /// Represents a disposable resource whose disposal invocation will be scheduled on the specified <seealso cref="IScheduler"/>.
  10. /// </summary>
  11. public sealed class ScheduledDisposable : ICancelable
  12. {
  13. private IDisposable _disposable;
  14. /// <summary>
  15. /// Initializes a new instance of the <see cref="ScheduledDisposable"/> class that uses an <see cref="IScheduler"/> on which to dispose the disposable.
  16. /// </summary>
  17. /// <param name="scheduler">Scheduler where the disposable resource will be disposed on.</param>
  18. /// <param name="disposable">Disposable resource to dispose on the given scheduler.</param>
  19. /// <exception cref="ArgumentNullException"><paramref name="scheduler"/> or <paramref name="disposable"/> is null.</exception>
  20. public ScheduledDisposable(IScheduler scheduler, IDisposable disposable)
  21. {
  22. if (disposable == null)
  23. {
  24. throw new ArgumentNullException(nameof(disposable));
  25. }
  26. Scheduler = scheduler ?? throw new ArgumentNullException(nameof(scheduler));
  27. Disposables.Disposable.SetSingle(ref _disposable, disposable);
  28. }
  29. /// <summary>
  30. /// Gets the scheduler where the disposable resource will be disposed on.
  31. /// </summary>
  32. public IScheduler Scheduler { get; }
  33. /// <summary>
  34. /// Gets the underlying disposable. After disposal, the result is undefined.
  35. /// </summary>
  36. public IDisposable Disposable => Disposables.Disposable.GetValueOrDefault(ref _disposable);
  37. /// <summary>
  38. /// Gets a value that indicates whether the object is disposed.
  39. /// </summary>
  40. public bool IsDisposed => Disposables.Disposable.GetIsDisposed(ref _disposable);
  41. /// <summary>
  42. /// Disposes the wrapped disposable on the provided scheduler.
  43. /// </summary>
  44. public void Dispose() => Scheduler.ScheduleAction(this, scheduler => Disposables.Disposable.Dispose(ref scheduler._disposable));
  45. }
  46. }