Never.cs 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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>()
  12. {
  13. return NeverAsyncEnumerable<TValue>.Instance;
  14. }
  15. private sealed class NeverAsyncEnumerable<TValue> : IAsyncEnumerable<TValue>
  16. {
  17. internal static readonly NeverAsyncEnumerable<TValue> Instance = new NeverAsyncEnumerable<TValue>();
  18. public IAsyncEnumerator<TValue> GetAsyncEnumerator(CancellationToken cancellationToken)
  19. {
  20. return new NeverAsyncEnumerator(cancellationToken);
  21. }
  22. private sealed class NeverAsyncEnumerator : IAsyncEnumerator<TValue>
  23. {
  24. private readonly CancellationToken _token;
  25. private CancellationTokenRegistration _registration;
  26. private bool _once;
  27. private TaskCompletionSource<bool> _task;
  28. public NeverAsyncEnumerator(CancellationToken token)
  29. {
  30. _token = token;
  31. }
  32. public TValue Current => throw new InvalidOperationException();
  33. public ValueTask DisposeAsync()
  34. {
  35. _registration.Dispose();
  36. _task = null;
  37. return default;
  38. }
  39. public ValueTask<bool> MoveNextAsync()
  40. {
  41. if (_once)
  42. {
  43. return new ValueTask<bool>(false);
  44. }
  45. _once = true;
  46. _task = new TaskCompletionSource<bool>();
  47. _registration = _token.Register(state => ((NeverAsyncEnumerator)state)._task.SetCanceled(), this);
  48. return new ValueTask<bool>(_task.Task);
  49. }
  50. }
  51. }
  52. }
  53. }