Example #1
0
            public override async Task <int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
            {
                if (count == 0)
                {
                    return(0);
                }

                if (_reader == null)
                {
                    if (_message.Properties.ContainsKey(BufferedReadStream.BufferedReadStreamPropertyName))
                    {
                        _bufferedReadStream =
                            _message.Properties[BufferedReadStream.BufferedReadStreamPropertyName] as BufferedReadStream;
                    }
                }

                using (TaskHelpers.RunTaskContinuationsOnOurThreads())
                {
                    if (_bufferedReadStream != null)
                    {
                        await _bufferedReadStream.PreReadBufferAsync(cancellationToken);
                    }

                    return(Read(buffer, offset, count));
                }
            }
Example #2
0
        private async Task <Stream> GetStreamAsync(TimeoutHelper timeoutHelper)
        {
            var    content       = _httpResponseMessage.Content;
            Stream contentStream = null;

            _contentLength = -1;
            if (content != null)
            {
                contentStream = await content.ReadAsStreamAsync();

                _contentLength = content.Headers.ContentLength.HasValue ? content.Headers.ContentLength.Value : -1;
                var cancellationToken = await timeoutHelper.GetCancellationTokenAsync();

                if (_contentLength <= 0)
                {
                    var preReadBuffer = new byte[1];
                    if (await contentStream.ReadAsync(preReadBuffer, 0, 1, cancellationToken) == 0)
                    {
                        contentStream.Dispose();
                        contentStream = null;
                    }
                    else
                    {
                        var bufferedStream = new BufferedReadStream(contentStream, _factory.BufferManager);
                        await bufferedStream.PreReadBufferAsync(preReadBuffer[0], cancellationToken);

                        contentStream = bufferedStream;
                    }
                }
                else if (TransferModeHelper.IsResponseStreamed(_factory.TransferMode))
                {
                    // If _contentLength > 0, then the message was sent buffered but we might still
                    // be receiving it streamed. In which case we need a buffered reading stream.
                    var bufferedStream = new BufferedReadStream(contentStream, _factory.BufferManager);
                    await bufferedStream.PreReadBufferAsync(cancellationToken);

                    contentStream = bufferedStream;
                }
            }

            return(contentStream);
        }