ContextDisposable.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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.Reactive.Concurrency;
  5. using System.Threading;
  6. namespace System.Reactive.Disposables
  7. {
  8. /// <summary>
  9. /// Represents a disposable resource whose disposal invocation will be posted to the specified <seealso cref="SynchronizationContext"/>.
  10. /// </summary>
  11. public sealed class ContextDisposable : ICancelable
  12. {
  13. private IDisposable _disposable;
  14. /// <summary>
  15. /// Initializes a new instance of the <see cref="ContextDisposable"/> class that uses the specified <see cref="SynchronizationContext"/> on which to dispose the specified disposable resource.
  16. /// </summary>
  17. /// <param name="context">Context to perform disposal on.</param>
  18. /// <param name="disposable">Disposable whose Dispose operation to run on the given synchronization context.</param>
  19. /// <exception cref="ArgumentNullException"><paramref name="context"/> or <paramref name="disposable"/> is null.</exception>
  20. public ContextDisposable(SynchronizationContext context, IDisposable disposable)
  21. {
  22. if (disposable == null)
  23. {
  24. throw new ArgumentNullException(nameof(disposable));
  25. }
  26. Context = context ?? throw new ArgumentNullException(nameof(context));
  27. Disposable.SetSingle(ref _disposable, disposable);
  28. }
  29. /// <summary>
  30. /// Gets the provided <see cref="SynchronizationContext"/>.
  31. /// </summary>
  32. public SynchronizationContext Context { get; }
  33. /// <summary>
  34. /// Gets a value that indicates whether the object is disposed.
  35. /// </summary>
  36. public bool IsDisposed => Disposable.GetIsDisposed(ref _disposable);
  37. /// <summary>
  38. /// Disposes the underlying disposable on the provided <see cref="SynchronizationContext"/>.
  39. /// </summary>
  40. public void Dispose()
  41. {
  42. Disposable.TryRelease(ref _disposable, Context, static (disposable, context) => context.PostWithStartComplete(static d => d.Dispose(), disposable));
  43. }
  44. }
  45. }