public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
// Validate arguments as would the base CopyToAsync
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
// And bail early if cancellation has already been requested
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled(cancellationToken);
}
// Then do additional checks as ReadAsync would.
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
Socket streamSocket = _streamSocket;
if (streamSocket == null)
{
throw new IOException(SR.Format(SR.net_io_readfailure, SR.net_io_connectionclosed));
}
// Do the copy. We get a copy buffer from the shared pool, and we pass both it and the
// socket into the copy as part of the event args so as to avoid additional fields in
// the async method's state machine.
return CopyToAsyncCore(
destination,
new AwaitableSocketAsyncEventArgs(streamSocket, ArrayPool<byte>.Shared.Rent(bufferSize)),
cancellationToken);
}