Question

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?

Was it helpful?

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.

OTHER TIPS

I may say that the built-in implementation is CopyToAsync with CancellationToken.

In my opinion you will spend less time implementing CopyToAsync (instead of CopyTo) than building your own implementation of Cancellation (and less risk of errors/bugs).

For the case that no better answer arrives: You can implement a synchronous copy loop with 10 lines of C# as a reusable helper method. Take a peek with Reflector how this is done.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top