Never.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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.Runtime.CompilerServices;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. namespace System.Linq
  9. {
  10. public static partial class AsyncEnumerableEx
  11. {
  12. public static IAsyncEnumerable<TValue> Never<TValue>()
  13. {
  14. return NeverAsyncEnumerable<TValue>.Instance;
  15. }
  16. private sealed class NeverAsyncEnumerable<TValue> : IAsyncEnumerable<TValue>
  17. {
  18. internal static readonly NeverAsyncEnumerable<TValue> Instance = new NeverAsyncEnumerable<TValue>();
  19. public IAsyncEnumerator<TValue> GetAsyncEnumerator(CancellationToken cancellationToken = default)
  20. {
  21. return new NeverAsyncEnumerator(cancellationToken);
  22. }
  23. private sealed class NeverAsyncEnumerator : IAsyncEnumerator<TValue>
  24. {
  25. public TValue Current => throw new InvalidOperationException();
  26. private readonly CancellationToken _token;
  27. public NeverAsyncEnumerator(CancellationToken token)
  28. {
  29. _token = token;
  30. }
  31. public ValueTask DisposeAsync()
  32. {
  33. return TaskExt.CompletedTask;
  34. }
  35. public ValueTask<bool> MoveNextAsync()
  36. {
  37. return new ValueTask<bool>(Task.Run(async () =>
  38. {
  39. await Task.Delay(Threading.Timeout.Infinite, _token);
  40. return false;
  41. }, _token));
  42. }
  43. }
  44. }
  45. }
  46. }