Timeout.cs 5.0 KB

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