Never.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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)
  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. private CancellationTokenRegistration _registration;
  28. private bool _once;
  29. private TaskCompletionSource<bool> _task;
  30. public NeverAsyncEnumerator(CancellationToken token)
  31. {
  32. _token = token;
  33. }
  34. public ValueTask DisposeAsync()
  35. {
  36. _registration.Dispose();
  37. _task = null;
  38. return TaskExt.CompletedTask;
  39. }
  40. public ValueTask<bool> MoveNextAsync()
  41. {
  42. if (_once)
  43. {
  44. return TaskExt.False;
  45. }
  46. _once = true;
  47. _task = new TaskCompletionSource<bool>();
  48. _registration = _token.Register(state => ((NeverAsyncEnumerator)state)._task.SetCanceled(), this);
  49. return new ValueTask<bool>(_task.Task);
  50. }
  51. }
  52. }
  53. }
  54. }