AsyncDisposable.cs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT 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<ValueTask> 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<ValueTask> _dispose;
  20. public AnonymousAsyncDisposable(Func<ValueTask> dispose) => _dispose = dispose;
  21. public ValueTask DisposeAsync() => Interlocked.Exchange(ref _dispose, null)?.Invoke() ?? default;
  22. }
  23. private sealed class NopAsyncDisposable : IAsyncDisposable
  24. {
  25. public ValueTask DisposeAsync() => default;
  26. }
  27. }
  28. }