Skip to content

Commit 49e7fe5

Browse files
Better use of arraypool in stream copy.
1 parent 40d7369 commit 49e7fe5

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

source/Extensions.Stream.cs

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
using System;
2+
using System.Buffers;
23
using System.IO;
34

45
namespace Open.Collections
@@ -8,18 +9,26 @@ public static partial class Extensions
89
/// <summary>
910
/// Copies the source stream to the target.
1011
/// </summary>
11-
public static void CopyTo(this Stream source, Stream target)
12+
public static void CopyTo(this Stream source, Stream target, int bufferSize = 4096, bool clearBufferAfter = false)
1213
{
1314
if (source is null)
1415
throw new NullReferenceException();
1516
if (target is null)
1617
throw new ArgumentNullException(nameof(target));
1718

18-
var bytes = System.Buffers.ArrayPool<byte>.Shared.Rent(4096);
19-
int cnt;
20-
while ((cnt = source.Read(bytes, 0, bytes.Length)) != 0)
21-
target.Write(bytes, 0, cnt);
22-
System.Buffers.ArrayPool<byte>.Shared.Return(bytes, true);
19+
var pool = ArrayPool<byte>.Shared;
20+
var bytes = pool.Rent(bufferSize);
21+
22+
try
23+
{
24+
int cnt;
25+
while ((cnt = source.Read(bytes, 0, bufferSize)) != 0)
26+
target.Write(bytes, 0, cnt);
27+
}
28+
finally
29+
{
30+
pool.Return(bytes, clearBufferAfter);
31+
}
2332
}
2433
}
2534
}

0 commit comments

Comments
 (0)