Buffer.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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<IList<TSource>> Buffer<TSource>(this IAsyncEnumerable<TSource> source, int count)
  12. {
  13. if (source == null)
  14. throw Error.ArgumentNull(nameof(source));
  15. if (count <= 0)
  16. throw Error.ArgumentOutOfRange(nameof(count));
  17. return AsyncEnumerable.Create(Core);
  18. async IAsyncEnumerator<IList<TSource>> Core(CancellationToken cancellationToken)
  19. {
  20. var buffer = new List<TSource>(count);
  21. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  22. {
  23. buffer.Add(item);
  24. if (buffer.Count == count)
  25. {
  26. yield return buffer;
  27. buffer = new List<TSource>(count);
  28. }
  29. }
  30. if (buffer.Count > 0)
  31. {
  32. yield return buffer;
  33. }
  34. }
  35. }
  36. public static IAsyncEnumerable<IList<TSource>> Buffer<TSource>(this IAsyncEnumerable<TSource> source, int count, int skip)
  37. {
  38. if (source == null)
  39. throw Error.ArgumentNull(nameof(source));
  40. if (count <= 0)
  41. throw Error.ArgumentOutOfRange(nameof(count));
  42. if (skip <= 0)
  43. throw Error.ArgumentOutOfRange(nameof(skip));
  44. return AsyncEnumerable.Create(Core);
  45. async IAsyncEnumerator<IList<TSource>> Core(CancellationToken cancellationToken)
  46. {
  47. var buffers = new Queue<IList<TSource>>();
  48. var index = 0;
  49. await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
  50. {
  51. if (index++ % skip == 0)
  52. {
  53. buffers.Enqueue(new List<TSource>(count));
  54. }
  55. foreach (var buffer in buffers)
  56. {
  57. buffer.Add(item);
  58. }
  59. if (buffers.Count > 0 && buffers.Peek().Count == count)
  60. {
  61. yield return buffers.Dequeue();
  62. }
  63. }
  64. while (buffers.Count > 0)
  65. {
  66. yield return buffers.Dequeue();
  67. }
  68. }
  69. }
  70. }
  71. }