AnonymousDisposable.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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.Threading;
  5. namespace System.Reactive.Disposables
  6. {
  7. /// <summary>
  8. /// Represents an Action-based disposable.
  9. /// </summary>
  10. internal sealed class AnonymousDisposable : ICancelable
  11. {
  12. private volatile Action _dispose;
  13. /// <summary>
  14. /// Constructs a new disposable with the given action used for disposal.
  15. /// </summary>
  16. /// <param name="dispose">Disposal action which will be run upon calling Dispose.</param>
  17. public AnonymousDisposable(Action dispose)
  18. {
  19. System.Diagnostics.Debug.Assert(dispose != null);
  20. _dispose = dispose;
  21. }
  22. /// <summary>
  23. /// Gets a value that indicates whether the object is disposed.
  24. /// </summary>
  25. public bool IsDisposed
  26. {
  27. get { return _dispose == null; }
  28. }
  29. /// <summary>
  30. /// Calls the disposal action if and only if the current instance hasn't been disposed yet.
  31. /// </summary>
  32. public void Dispose()
  33. {
  34. #pragma warning disable 0420
  35. var dispose = Interlocked.Exchange(ref _dispose, null);
  36. #pragma warning restore 0420
  37. if (dispose != null)
  38. {
  39. dispose();
  40. }
  41. }
  42. }
  43. }