Skip to content

Commit 0558432

Browse files
Added cancellation token.
1 parent 6ba82e3 commit 0558432

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

source/Extensions.Stream.cs

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using System;
22
using System.Buffers;
33
using System.IO;
4+
using System.Threading;
45
using System.Threading.Tasks;
56

67
namespace Open.Collections
@@ -10,7 +11,12 @@ public static partial class Extensions
1011
/// <summary>
1112
/// Copies the source stream to the target.
1213
/// </summary>
13-
public static async ValueTask DualBufferCopyToAsync(this Stream source, Stream target, int bufferSize = 4096, bool clearBufferAfter = false)
14+
public static async ValueTask DualBufferCopyToAsync(
15+
this Stream source,
16+
Stream target,
17+
int bufferSize = 4096,
18+
bool clearBufferAfter = false,
19+
CancellationToken? cancellationToken = null)
1420
{
1521
if (source is null)
1622
throw new NullReferenceException();
@@ -21,17 +27,18 @@ public static async ValueTask DualBufferCopyToAsync(this Stream source, Stream t
2127
var cNext = pool.Rent(bufferSize);
2228
var cCurrent = pool.Rent(bufferSize);
2329

30+
var token = cancellationToken ?? CancellationToken.None;
2431
try
2532
{
26-
var next = source.ReadAsync(cNext, 0, bufferSize);
33+
var next = source.ReadAsync(cNext, 0, bufferSize, token);
2734
while (true)
2835
{
2936
var n = await next.ConfigureAwait(false);
3037
if (n == 0) break;
3138

3239
// Preemptive request before yielding.
33-
var current = source.ReadAsync(cCurrent, 0, bufferSize);
34-
await target.WriteAsync(cNext, 0, n);
40+
var current = source.ReadAsync(cCurrent, 0, bufferSize, token);
41+
await target.WriteAsync(cNext, 0, n, token);
3542

3643
var swap = cNext;
3744
cNext = cCurrent;

0 commit comments

Comments
 (0)