Never.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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.Collections.Generic;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. namespace System.Linq
  8. {
  9. public static partial class AsyncEnumerableEx
  10. {
  11. public static IAsyncEnumerable<TValue> Never<TValue>() => NeverAsyncEnumerable<TValue>.Instance;
  12. private sealed class NeverAsyncEnumerable<TValue> : IAsyncEnumerable<TValue>
  13. {
  14. internal static readonly NeverAsyncEnumerable<TValue> Instance = new NeverAsyncEnumerable<TValue>();
  15. public IAsyncEnumerator<TValue> GetAsyncEnumerator(CancellationToken cancellationToken)
  16. {
  17. cancellationToken.ThrowIfCancellationRequested(); // NB: [LDM-2018-11-28] Equivalent to async iterator behavior.
  18. return new NeverAsyncEnumerator(cancellationToken);
  19. }
  20. private sealed class NeverAsyncEnumerator : IAsyncEnumerator<TValue>
  21. {
  22. private readonly CancellationToken _token;
  23. private CancellationTokenRegistration _registration;
  24. private bool _once;
  25. private TaskCompletionSource<bool> _task;
  26. public NeverAsyncEnumerator(CancellationToken token) => _token = token;
  27. public TValue Current => throw new InvalidOperationException();
  28. public ValueTask DisposeAsync()
  29. {
  30. _registration.Dispose();
  31. _task = null;
  32. return default;
  33. }
  34. public ValueTask<bool> MoveNextAsync()
  35. {
  36. if (_once)
  37. {
  38. return new ValueTask<bool>(false);
  39. }
  40. _once = true;
  41. _task = new TaskCompletionSource<bool>();
  42. _registration = _token.Register(state => ((NeverAsyncEnumerator)state)._task.SetCanceled(), this);
  43. return new ValueTask<bool>(_task.Task);
  44. }
  45. }
  46. }
  47. }
  48. }