public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
// If we're in sync mode, just use the shared CopyToAsync implementation that does
// typical read/write looping. We also need to take this path if this is a derived
// instance from FileStream, as a derived type could have overridden ReadAsync, in which
// case our custom CopyToAsync implementation isn't necessarily correct.
if (!_useAsyncIO || GetType() != typeof(FileStream))
{
return base.CopyToAsync(destination, bufferSize, cancellationToken);
}
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
// Bail early for cancellation if cancellation has been requested
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<int>(cancellationToken);
}
// Fail if the file was closed
if (_fileHandle.IsClosed)
{
throw Error.GetFileNotOpen();
}
// Do the async copy, with differing implementations based on whether the FileStream was opened as async or sync
Debug.Assert((_readPos == 0 && _readLength == 0 && _writePos >= 0) || (_writePos == 0 && _readPos <= _readLength), "We're either reading or writing, but not both.");
return AsyncModeCopyToAsync(destination, bufferSize, cancellationToken);
}