AsyncDisposable.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  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. using System.Threading.Tasks;
  6. namespace System.Reactive.Disposables
  7. {
  8. public static class AsyncDisposable
  9. {
  10. public static IAsyncDisposable Nop { get; } = new NopAsyncDisposable();
  11. public static IAsyncDisposable Create(Func<Task> dispose)
  12. {
  13. if (dispose == null)
  14. throw new ArgumentNullException(nameof(dispose));
  15. return new AnonymousAsyncDisposable(dispose);
  16. }
  17. private sealed class AnonymousAsyncDisposable : IAsyncDisposable
  18. {
  19. private Func<Task> _dispose;
  20. public AnonymousAsyncDisposable(Func<Task> dispose)
  21. {
  22. _dispose = dispose;
  23. }
  24. public Task DisposeAsync() => Interlocked.Exchange(ref _dispose, null)?.Invoke() ?? Task.CompletedTask;
  25. }
  26. private sealed class NopAsyncDisposable : IAsyncDisposable
  27. {
  28. public Task DisposeAsync() => Task.CompletedTask;
  29. }
  30. }
  31. }