Timeout.cs 5.1 KB

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