1
0

ContextDisposable.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. #if !NO_SYNCCTX
  5. using System.Reactive.Concurrency;
  6. using System.Threading;
  7. namespace System.Reactive.Disposables
  8. {
  9. /// <summary>
  10. /// Represents a disposable resource whose disposal invocation will be posted to the specified <seealso cref="T:System.Threading.SynchronizationContext"/>.
  11. /// </summary>
  12. public sealed class ContextDisposable : ICancelable
  13. {
  14. private readonly SynchronizationContext _context;
  15. private volatile IDisposable _disposable;
  16. /// <summary>
  17. /// Initializes a new instance of the <see cref="T:System.Reactive.Disposables.ContextDisposable"/> class that uses the specified <see cref="T:System.Threading.SynchronizationContext"/> on which to dispose the specified disposable resource.
  18. /// </summary>
  19. /// <param name="context">Context to perform disposal on.</param>
  20. /// <param name="disposable">Disposable whose Dispose operation to run on the given synchronization context.</param>
  21. /// <exception cref="ArgumentNullException"><paramref name="context"/> or <paramref name="disposable"/> is null.</exception>
  22. public ContextDisposable(SynchronizationContext context, IDisposable disposable)
  23. {
  24. if (context == null)
  25. throw new ArgumentNullException("context");
  26. if (disposable == null)
  27. throw new ArgumentNullException("disposable");
  28. _context = context;
  29. _disposable = disposable;
  30. }
  31. /// <summary>
  32. /// Gets the provided <see cref="T:System.Threading.SynchronizationContext"/>.
  33. /// </summary>
  34. public SynchronizationContext Context
  35. {
  36. get { return _context; }
  37. }
  38. /// <summary>
  39. /// Gets a value that indicates whether the object is disposed.
  40. /// </summary>
  41. public bool IsDisposed
  42. {
  43. get { return _disposable == BooleanDisposable.True; }
  44. }
  45. /// <summary>
  46. /// Disposes the underlying disposable on the provided <see cref="T:System.Threading.SynchronizationContext"/>.
  47. /// </summary>
  48. public void Dispose()
  49. {
  50. #pragma warning disable 0420
  51. var disposable = Interlocked.Exchange(ref _disposable, BooleanDisposable.True);
  52. #pragma warning restore 0420
  53. if (disposable != BooleanDisposable.True)
  54. {
  55. _context.PostWithStartComplete(d => d.Dispose(), disposable);
  56. }
  57. }
  58. }
  59. }
  60. #endif