1
0

Never.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. public NeverAsyncEnumerator(CancellationToken token) => _token = token;
  26. public TValue Current => throw new InvalidOperationException();
  27. public ValueTask DisposeAsync()
  28. {
  29. _registration.Dispose();
  30. return default;
  31. }
  32. public ValueTask<bool> MoveNextAsync()
  33. {
  34. if (_once)
  35. {
  36. return new ValueTask<bool>(false);
  37. }
  38. _once = true;
  39. var task = new TaskCompletionSource<bool>();
  40. _registration = _token.Register(state => ((TaskCompletionSource<bool>)state).SetCanceled(), task);
  41. return new ValueTask<bool>(task.Task);
  42. }
  43. }
  44. }
  45. }
  46. }