Buffer.cs 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. namespace System.Linq
  10. {
  11. public static partial class AsyncEnumerable
  12. {
  13. public static IAsyncEnumerable<IList<TSource>> Buffer<TSource>(this IAsyncEnumerable<TSource> source, int count)
  14. {
  15. if (source == null)
  16. throw new ArgumentNullException(nameof(source));
  17. if (count <= 0)
  18. throw new ArgumentOutOfRangeException(nameof(count));
  19. return source.Buffer_(count, count);
  20. }
  21. public static IAsyncEnumerable<IList<TSource>> Buffer<TSource>(this IAsyncEnumerable<TSource> source, int count, int skip)
  22. {
  23. if (source == null)
  24. throw new ArgumentNullException(nameof(source));
  25. if (count <= 0)
  26. throw new ArgumentOutOfRangeException(nameof(count));
  27. if (skip <= 0)
  28. throw new ArgumentOutOfRangeException(nameof(skip));
  29. return source.Buffer_(count, skip);
  30. }
  31. private static IAsyncEnumerable<IList<TSource>> Buffer_<TSource>(this IAsyncEnumerable<TSource> source, int count, int skip)
  32. {
  33. return Create(() =>
  34. {
  35. var e = source.GetEnumerator();
  36. var cts = new CancellationTokenDisposable();
  37. var d = Disposable.Create(cts, e);
  38. var buffers = new Queue<IList<TSource>>();
  39. var i = 0;
  40. var current = default(IList<TSource>);
  41. var stopped = false;
  42. var f = default(Func<CancellationToken, Task<bool>>);
  43. f = async ct =>
  44. {
  45. if (!stopped)
  46. {
  47. if (await e.MoveNext(ct)
  48. .ConfigureAwait(false))
  49. {
  50. var item = e.Current;
  51. if (i++%skip == 0)
  52. buffers.Enqueue(new List<TSource>(count));
  53. foreach (var buffer in buffers)
  54. buffer.Add(item);
  55. if (buffers.Count > 0 && buffers.Peek()
  56. .Count == count)
  57. {
  58. current = buffers.Dequeue();
  59. return true;
  60. }
  61. return await f(ct)
  62. .ConfigureAwait(false);
  63. }
  64. stopped = true;
  65. e.Dispose();
  66. return await f(ct)
  67. .ConfigureAwait(false);
  68. }
  69. if (buffers.Count > 0)
  70. {
  71. current = buffers.Dequeue();
  72. return true;
  73. }
  74. return false;
  75. };
  76. return Create(
  77. f,
  78. () => current,
  79. d.Dispose,
  80. e
  81. );
  82. });
  83. }
  84. }
  85. }