CopyTo with CancellationToken argument

.net, c#, cancellation-token

Solution

I have just taken .NET CopyTo implementation and added one line in the cycle:

public static void CopyTo(this Stream source, Stream destination, int bufferSize, CancellationToken cancellationToken)
{
    var buffer = new byte[bufferSize];
    int count;
    while ((count = source.Read(buffer, 0, buffer.Length)) != 0)
    {
        cancellationToken.ThrowIfCancellationRequested();
        destination.Write(buffer, 0, count);
    }
}

But I find it disappointing .NET Framework designers don't care about cancellation of long-running synchronous operations.

Problem

I see `CopyToAsync` has `CancellationToken` argument. But I don't need `CopyToAsync` as my code is already executed in background thread. I just want to have `CopyTo` overload which takes `CancellationToken` and checks it every time it copies bufferSize amount of bytes. Is there any built in implementation?

Original source