We can improve performance for streaming HTTP responses by using HttpCompletionOption.ResponseHeadersRead when making the request. This will allow the response to be streamed rather than copying the entire response to a buffer before returning.
However, there are dangers that may need to be addressed:
I've seen cases with JSON deserialization throwing exceptions when reading from a non-buffered stream on legacy .NET Framework, such as problems with the connection closing while the stream is being read.
In legacy .NET Framework failure to Dispose of the HttpResponseMessage can lead to leaked HTTP connections which then impact the ServicePointManager maximum number of connections per server and other resources. It's still desired to Dispose in .NET Core/5/6, but there is a finalizer to help mitigate the problem and there are no per-server limits by default.
We can improve performance for streaming HTTP responses by using
HttpCompletionOption.ResponseHeadersRead
when making the request. This will allow the response to be streamed rather than copying the entire response to a buffer before returning.However, there are dangers that may need to be addressed:
Dispose
of theHttpResponseMessage
can lead to leaked HTTP connections which then impact theServicePointManager
maximum number of connections per server and other resources. It's still desired toDispose
in .NET Core/5/6, but there is a finalizer to help mitigate the problem and there are no per-server limits by default.For these reasons, we may want to consider:
Stream
result types