SingleAssignmentAsyncDisposable.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  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 sealed class SingleAssignmentAsyncDisposable : IAsyncDisposable
  9. {
  10. private static readonly IAsyncDisposable Disposed = AsyncDisposable.Create(() => default);
  11. private IAsyncDisposable _disposable;
  12. public async ValueTask AssignAsync(IAsyncDisposable disposable)
  13. {
  14. if (disposable == null)
  15. throw new ArgumentNullException(nameof(disposable));
  16. var old = Interlocked.CompareExchange(ref _disposable, disposable, null);
  17. if (old == null)
  18. return;
  19. if (old != Disposed)
  20. throw new InvalidOperationException("Disposable already assigned.");
  21. await disposable.DisposeAsync().ConfigureAwait(false);
  22. }
  23. public ValueTask DisposeAsync()
  24. {
  25. return Interlocked.Exchange(ref _disposable, Disposed)?.DisposeAsync() ?? default;
  26. }
  27. }
  28. }