1
0

Timeout.cs 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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.Diagnostics;
  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<TSource> Timeout<TSource>(this IAsyncEnumerable<TSource> source, TimeSpan timeout)
  13. {
  14. if (source == null)
  15. throw Error.ArgumentNull(nameof(source));
  16. var num = (long)timeout.TotalMilliseconds;
  17. if (num < -1L || num > int.MaxValue)
  18. throw Error.ArgumentOutOfRange(nameof(timeout));
  19. return new TimeoutAsyncIterator<TSource>(source, timeout);
  20. }
  21. private sealed class TimeoutAsyncIterator<TSource> : AsyncIterator<TSource>
  22. {
  23. private readonly IAsyncEnumerable<TSource> _source;
  24. private readonly TimeSpan _timeout;
  25. private IAsyncEnumerator<TSource> _enumerator;
  26. public TimeoutAsyncIterator(IAsyncEnumerable<TSource> source, TimeSpan timeout)
  27. {
  28. Debug.Assert(source != null);
  29. _source = source;
  30. _timeout = timeout;
  31. }
  32. public override AsyncIterator<TSource> Clone()
  33. {
  34. return new TimeoutAsyncIterator<TSource>(_source, _timeout);
  35. }
  36. public override async ValueTask DisposeAsync()
  37. {
  38. if (_enumerator != null)
  39. {
  40. await _enumerator.DisposeAsync().ConfigureAwait(false);
  41. _enumerator = null;
  42. }
  43. await base.DisposeAsync().ConfigureAwait(false);
  44. }
  45. protected override async ValueTask<bool> MoveNextCore()
  46. {
  47. switch (_state)
  48. {
  49. case AsyncIteratorState.Allocated:
  50. _enumerator = _source.GetAsyncEnumerator(_cancellationToken);
  51. _state = AsyncIteratorState.Iterating;
  52. goto case AsyncIteratorState.Iterating;
  53. case AsyncIteratorState.Iterating:
  54. var moveNext = _enumerator.MoveNextAsync();
  55. if (!moveNext.IsCompleted)
  56. {
  57. using (var delayCts = new CancellationTokenSource())
  58. {
  59. var delay = Task.Delay(_timeout, delayCts.Token);
  60. var winner = await Task.WhenAny(moveNext.AsTask(), delay).ConfigureAwait(false);
  61. if (winner == delay)
  62. {
  63. throw new TimeoutException();
  64. }
  65. delayCts.Cancel();
  66. }
  67. }
  68. if (await moveNext.ConfigureAwait(false))
  69. {
  70. _current = _enumerator.Current;
  71. return true;
  72. }
  73. break;
  74. }
  75. await DisposeAsync().ConfigureAwait(false);
  76. return false;
  77. }
  78. }
  79. }
  80. }