ScheduledDisposable.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the Apache 2.0 License.
  3. // See the LICENSE file in the project root for more information.
  4. using System.Reactive.Concurrency;
  5. namespace System.Reactive.Disposables
  6. {
  7. /// <summary>
  8. /// Represents a disposable resource whose disposal invocation will be scheduled on the specified <seealso cref="IScheduler"/>.
  9. /// </summary>
  10. public sealed class ScheduledDisposable : ICancelable
  11. {
  12. private IDisposable _disposable;
  13. /// <summary>
  14. /// Initializes a new instance of the <see cref="ScheduledDisposable"/> class that uses an <see cref="IScheduler"/> on which to dispose the disposable.
  15. /// </summary>
  16. /// <param name="scheduler">Scheduler where the disposable resource will be disposed on.</param>
  17. /// <param name="disposable">Disposable resource to dispose on the given scheduler.</param>
  18. /// <exception cref="ArgumentNullException"><paramref name="scheduler"/> or <paramref name="disposable"/> is null.</exception>
  19. public ScheduledDisposable(IScheduler scheduler, IDisposable disposable)
  20. {
  21. if (disposable == null)
  22. {
  23. throw new ArgumentNullException(nameof(disposable));
  24. }
  25. Scheduler = scheduler ?? throw new ArgumentNullException(nameof(scheduler));
  26. Disposables.Disposable.SetSingle(ref _disposable, disposable);
  27. }
  28. /// <summary>
  29. /// Gets the scheduler where the disposable resource will be disposed on.
  30. /// </summary>
  31. public IScheduler Scheduler { get; }
  32. /// <summary>
  33. /// Gets the underlying disposable. After disposal, the result is undefined.
  34. /// </summary>
  35. public IDisposable Disposable => Disposables.Disposable.GetValueOrDefault(ref _disposable);
  36. /// <summary>
  37. /// Gets a value that indicates whether the object is disposed.
  38. /// </summary>
  39. public bool IsDisposed => Disposables.Disposable.GetIsDisposed(ref _disposable);
  40. /// <summary>
  41. /// Disposes the wrapped disposable on the provided scheduler.
  42. /// </summary>
  43. public void Dispose() => Scheduler.ScheduleAction(this, scheduler => Disposables.Disposable.TryDispose(ref scheduler._disposable));
  44. }
  45. }