DisposeAction.cs 909 B

123456789101112131415161718192021222324252627282930313233
  1. using System;
  2. using System.Threading;
  3. using JetBrains.Annotations;
  4. namespace Abp
  5. {
  6. /// <summary>
  7. /// This class can be used to provide an action when
  8. /// Dipose method is called.
  9. /// </summary>
  10. public class DisposeAction : IDisposable
  11. {
  12. public static readonly DisposeAction Empty = new DisposeAction(null);
  13. private Action _action;
  14. /// <summary>
  15. /// Creates a new <see cref="DisposeAction"/> object.
  16. /// </summary>
  17. /// <param name="action">Action to be executed when this object is disposed.</param>
  18. public DisposeAction([CanBeNull] Action action)
  19. {
  20. _action = action;
  21. }
  22. public void Dispose()
  23. {
  24. // Interlocked prevents multiple execution of the _action.
  25. var action = Interlocked.Exchange(ref _action, null);
  26. action?.Invoke();
  27. }
  28. }
  29. }