Timeout.cs 4.8 KB

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