Timeout.cs 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  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<TSource> Timeout<TSource>(this IAsyncEnumerable<TSource> source, TimeSpan timeout)
  12. {
  13. if (source == null)
  14. throw Error.ArgumentNull(nameof(source));
  15. var num = (long)timeout.TotalMilliseconds;
  16. if (num < -1L || num > int.MaxValue)
  17. throw Error.ArgumentOutOfRange(nameof(timeout));
  18. return new TimeoutAsyncIterator<TSource>(source, timeout);
  19. }
  20. private sealed class TimeoutAsyncIterator<TSource> : AsyncIterator<TSource>
  21. {
  22. private readonly IAsyncEnumerable<TSource> _source;
  23. private readonly TimeSpan _timeout;
  24. private IAsyncEnumerator<TSource>? _enumerator;
  25. private Task? _loserTask;
  26. public TimeoutAsyncIterator(IAsyncEnumerable<TSource> source, TimeSpan timeout)
  27. {
  28. _source = source;
  29. _timeout = timeout;
  30. }
  31. public override AsyncIteratorBase<TSource> Clone()
  32. {
  33. return new TimeoutAsyncIterator<TSource>(_source, _timeout);
  34. }
  35. public override async ValueTask DisposeAsync()
  36. {
  37. if (_loserTask != null)
  38. {
  39. await _loserTask.ConfigureAwait(false);
  40. _loserTask = null;
  41. _enumerator = null;
  42. }
  43. else if (_enumerator != null)
  44. {
  45. await _enumerator.DisposeAsync().ConfigureAwait(false);
  46. _enumerator = null;
  47. }
  48. await base.DisposeAsync().ConfigureAwait(false);
  49. }
  50. protected override async ValueTask<bool> MoveNextCore()
  51. {
  52. switch (_state)
  53. {
  54. case AsyncIteratorState.Allocated:
  55. _enumerator = _source.GetAsyncEnumerator(_cancellationToken);
  56. _state = AsyncIteratorState.Iterating;
  57. goto case AsyncIteratorState.Iterating;
  58. case AsyncIteratorState.Iterating:
  59. var moveNext = _enumerator!.MoveNextAsync();
  60. if (!moveNext.IsCompleted)
  61. {
  62. using var delayCts = new CancellationTokenSource();
  63. var delay = Task.Delay(_timeout, delayCts.Token);
  64. var next = moveNext.AsTask();
  65. var winner = await Task.WhenAny(next, delay).ConfigureAwait(false);
  66. if (winner == delay)
  67. {
  68. // NB: We still have to wait for the MoveNextAsync operation to complete before we can
  69. // dispose _enumerator. The resulting task will be used by DisposeAsync. Also note
  70. // that throwing an exception here causes a call to DisposeAsync, where we pick up
  71. // the task prepared below.
  72. // NB: Any exception reported by a timed out MoveNextAsync operation won't be reported
  73. // to the caller, but the task's exception is not marked as observed, so unhandled
  74. // exception handlers can still observe the exception.
  75. // REVIEW: Should exceptions reported by a timed out MoveNextAsync operation come out
  76. // when attempting to call DisposeAsync?
  77. _loserTask = next.ContinueWith((_, state) => ((IAsyncDisposable)state!).DisposeAsync().AsTask(), _enumerator);
  78. throw new TimeoutException();
  79. }
  80. delayCts.Cancel();
  81. }
  82. if (await moveNext.ConfigureAwait(false))
  83. {
  84. _current = _enumerator.Current;
  85. return true;
  86. }
  87. break;
  88. }
  89. await DisposeAsync().ConfigureAwait(false);
  90. return false;
  91. }
  92. }
  93. }
  94. }