AnonymousDisposable.cs 1.4 KB

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