Timeout.cs 5.0 KB

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